悬挂指针示例混淆

Dangling pointer example confusion

为什么下面的例子不正确?为什么它不显示 悬挂指针 ?我的老师说它不显示悬挂指针。提前致谢!

int X = 32;
int *p = &X;
free(p);
*p = 32; //<------Shouldn't this line cause dangling pointer ???

这里也是一样。为什么以下示例没有演示 内存泄漏

void function(int x){
   int *p = &x;
   *p = 32;
   //shouln't this code show a warning as p was not freed?
}

因为 X 没有分配到堆上,所以不能释放 p。要释放,您必须使用 malloc、calloc 或 realloc。

同样,在第二部分中,变量再次在堆栈上,将被自动清除。

第一个密码

这是未定义的行为。

N1256 7.20.3.2 自由函数

If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

第二个密码

此代码本身不会导致内存泄漏,因为它不会丢弃任何已分配的缓冲区。

引用维基百科:

Dangling pointer and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

此外,您应该 malloc 或类似分配函数分配的可用内存 - 在这两种情况下,您似乎都感到困惑。基本上 none 你的例子需要 free.

悬挂指针的一个例子是:

{
   char *ptr = NULL;

   {
       char c;
       ptr = &c;
   } 
     // c falls out of scope 
     // ptr is now a dangling pointer 
}

此外,如果您有这样的示例:

int *p = malloc(sizeof(int));
*p = 9;
free(p); // now p is dangling