提问人:Debojit 提问时间:8/12/2023 最后编辑:Etienne de MartelDebojit 更新时间:8/12/2023 访问量:52
为什么这个悬空的指针在释放内存后仍显示相同的内存地址?[复制]
Why this dangling pointer shows the same memory address even after freeing the memory? [duplicate]
问:
为什么释放内存后,以下程序中的悬空指针仍显示相同的内存地址?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 1;
int *ptr_a = (int*)malloc((sizeof(int)));
ptr_a = &a;
printf("The address of 'a' is %p\n", ptr_a);
free(ptr_a); // A dangling pointer
printf("The address of 'a' is %p", ptr_a);
return 0;
}
我尝试了一切,但仍然遇到同样的问题。
答:
1赞
Tom Karzes
8/12/2023
#1
代码首先通过调用 分配内存,并将返回的地址存储在 中。然后,它将局部变量的地址分配给 。此时,返回的内存地址丢失,导致永久内存泄漏。malloc
ptr_a
a
ptr_a
malloc
然后,它将 ,即 的地址传递给 。这是未定义的行为。您只能将 、 、 等获取的指针传递给 。ptr_a
a
free
malloc
realloc
calloc
free
存储在 中的指针不会因调用 而改变,因此它会打印相同的地址(除非由于对 的错误调用导致的未定义行为而出现严重错误)。ptr_a
free
free
评论
free
free
free(ptr)
free(&ptr);
ptr