代码如下。
我的问题是关于结果的。我想明白,为什么在调用 free(p) 之后 p->elem 变成 '0',但 p->str 仍然包含“hello”?
#define LEN (sizeof(struct node))
typedef struct node
{
int elem;
char *str;
}*p_node;
int main(void)
{
p_node p;
p=(p_node)malloc(LEN);
p->elem=99;
p->str="hello";
printf("the p->elem:%d\n",p->elem);
printf("the p->str :%s\n",p->str);
free(p);
printf("the p->elem:%d\n",p->elem);
printf("the p->str :%s\n",p->str);
return 0;
}
最佳答案
释放内存实际上并不会清除指针或其指向的内存(除非在特殊情况下旨在帮助调试此类问题 - 但永远不要依赖该行为)。释放指针所指向的内存后使用指针是无效的,并且是未定义的行为。它也可能会崩溃,或者导致打印随机值。
另外,在 C 语言中你应该 not cast the return of malloc
.
关于c - 我调用 free(),但指针仍然有数据并且其内容没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20801582/