S..*_*..K 3 c heap malloc free pointers
我有以下C代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int a;
}node;
int main()
{
node * n;
printf("\n%d\n",n->a);
n = (node *) malloc ( sizeof( node ));
printf("\n%d\n",n->a);
n->a = 6;
printf("\n%d\n",n->a);
free(n);
printf("\n%d\n",n->a);
n->a = 4;
printf("\n%d\n",n->a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
获得的输出是:
1314172
0
6
0
4
我的问题是即使在free(n)之后,为什么n-> a = 0,我们如何将它重新分配给任何值,如n-> a = 4?
不自由使n指向的内存块无效吗?
Pra*_*rav 15
free(n);
n->a = 4; // is not guaranteed to work, might crash on some implementations
Run Code Online (Sandbox Code Playgroud)
调用未定义的行为.
为什么n-> a = 0,我们怎样才能将它重新分配给n-> a = 4这样的任何值?
那是因为未定义的行为意味着任何事情都可能发生.你不能依赖它.
PS:不要写这样的代码.
编辑:
正如Jonathan注意到,您的代码在您之前很久free()就会引用未定义的行为,然后取消引用n.
node * n; //n is not initialized
printf("\n%d\n",n->a); //dereferencing a wild pointer invokes UB.
Run Code Online (Sandbox Code Playgroud)
nat*_*ose 13
重复使用已释放的指针类似于为您租用的汽车制作钥匙的副本,返回汽车,然后在您将汽车返回租赁地点后尝试使用该钥匙进入汽车.你可能能够逃脱它,但你不应该这样做,而且经常会让你遇到麻烦.