toa*_*eli 4 c malloc pointers memory-management
我目前正在学习C.我的讲师将此作为使用malloc和free的一个不好的例子,但对我来说似乎没问题.这是代码:
int *p1,**p2;
p1 = malloc(sizeof(int));
*p1 = 7;
p2 = malloc(sizeof(int*));
*p2 = p1;
free(p1);
free(*p2);
Run Code Online (Sandbox Code Playgroud)
我的讲师声称释放p1和*p2会导致"未定义的行为",但我不明白为什么.
我明白双重释放内存中相同的区域是坏的但不会*p2指向一个指向7的位置的指针?我认为他意味着做免费(p1)和免费(**p2)是坏事.我对吗?
也许一张照片会有所帮助.让我们假设第一个malloc返回地址0x10,第二个malloc返回地址0x30.所以在前五行代码之后,情况看起来像这样:
`p1` is a pointer with value `0x10`,
which points to memory that contains the integer value `7`.
`p2` is a pointer with value `0x30`,
which points to memory that contains a pointer with value `0x10` (a copy of the value in `p1`),
which points to memory that contains the integer value `7`.
Run Code Online (Sandbox Code Playgroud)
打电话后free(p1)你有这样的情况:
注意,这两个p1和*p2现在悬摆指针,它们都指向内存中的被释放.所以该行free(*p2)无效,你试图释放你已经释放的内存.相反,您想要free(p2)在位置释放内存0x30.