为什么在这种情况下不需要使用 free() 函数?

Why don't need to use free() function in this case?

所以这是一个简单的代码。我不会进一步解释。我的问题是,如果我使用 free() 它会导致

*** Error in `./main': free(): invalid pointer: 0x00007ffee58389f8 *** error,

但我不太明白为什么。是因为我给了ptr一个循环变量地址?如果我删除 free() 函数调用,它会完美运行,但我很好奇是什么原因造成的。

#include <stdio.h>
#include <stdlib.h>
int main()
{
  int num;
  printf("Give me a number:\n");
  scanf("%d", &num);

  int *ptr = malloc(sizeof(int) * num);

  for (int i = 0; i < num; ++i)
  {
    ptr = &i;
    printf("%d\n", *ptr);
  }
  free(ptr);
  return 0;
}

来自Valgrind

Definitely lost". This means that no pointer to the block can be found. The block is classified as "lost", because the programmer could not possibly have freed it at program exit, since no pointer to it exists. This is likely a symptom of having lost the pointer at some earlier point in the program. Such cases should be fixed by the programmer.

在代码中,指向 malloc 内存的指针已被修改 (ptr = &i) 因此,我们丢失了指向内存的指针。 而且,你不应该释放堆栈内存。

您传递给 free 的指针值必须 是由 malloccallocrealloc 返回的值.在这种情况下,您使用 i 的地址重新分配了 ptr,这是 而不是 *alloc 调用的结果。请注意,在此过程中,您丢失了对动态分配内存的唯一引用,因此您以后无法释放它;这称为内存泄漏。

如果你做类似 ptr++ 的事情,你会遇到同样的问题 - 你仍然指向动态分配的块内,但它又不是 *alloc 返回的地址,所以你得到同样的错误。