关于 free() 的 C 题
#include <stdio.h>
int main ()
{
int *p = (int *)malloc((100*sizeof(int)));
p++;
free(p);
/* do something */
return 0;
}
问题:
从 p+1 位置开始的内存是否会被释放(假设 malloc 返回 0x1000,则释放的内存将从 0x1004 开始,假设是 4 字节整数)?
除了从 0x1000 开始的 4 个字节(如果 malloc 返回 0x1000)不可用(除非你执行 p-- 并使用地址)这一事实之外,这段代码是否还有任何陷阱
#include <stdio.h>
int main ()
{
int *p = (int *)malloc((100*sizeof(int)));
p++;
free(p);
/* do something */
return 0;
}
Questions:
Will the memory starting from the location p+1 be free(say if malloc returned 0x1000, the memory freed will be from 0x1004,assuming a 4 byte integer)?
Are there anypitfalls of this code apart from the fact that the 4 bytes from 0x1000(if malloc returned 0x1000) are not useable (unless you do a p-- and use the address)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是未定义的行为 - 您必须将与从
malloc()
获取的指针完全相同的指针传递给free()
。对于您的代码,任何事情都可能发生 - 堆可能会被损坏。这样想吧。
free()
只有一个参数,因此它必须从该参数中推断出要标记为 free 的内容。没有办法“释放更少的内存” - 要么它会释放所有内存(顺便说一句,所需的扣除将非常耗时),或者发生不好的事情 - 后者更有可能。你不应该假设任何事情,只是不要这样做。That's undefined behavior - you must pass exactly the same pointer to
free()
as you obtained frommalloc()
. With your code anything can happen - likely heap will be corrupted.Think of it this way.
free()
has only one parameter, so it must deduce what to mark free from exactly that one parameter. There's no way to "free less memory" - either it will free all (deduction required for that will be very time-consuming btw), or something bad happens - the latter is more likely. You shouldn't assume anything, just don't do that.free() 调用将失败,因为 p 不再是用 malloc() 分配的块的地址。
The free() call will fail, because p is no longer the address of a block allocated with malloc().
这段代码不起作用 - 您只能释放由 malloc 或类似函数分配的指针,不能释放部分分配的内存范围。
This code just won't work - you can only free pointers that were allocated by malloc or similar function, you can't free part of the allocated memory range.
嘿,我通过 gcc 尝试了这段代码,结果停止了:
因此,根据您的第一个答案,您无法释放下一个内存位置。
对于第二个问题:
除非您执行 p-- ,否则这四个字节将无法使用,并且除非您更改下一个内存位置的内容并且可以通过执行 p-- 来使用分配的内存位置,否则此代码将正常工作
Hey I tried this code over gcc and it stopped with:
So as per your first answer you can't free the next memory location.
and for the second question:
and the four bytes won't be usable unless you do p-- and this code will work fine unless you change the contents of next memory location and you can use the allocated memory location by doing p--
在标准语言中,这种行为是“未定义的”,但实际上,没有任何东西会被释放。
原因是 malloc 保留了它已分配的块的列表,每个块都由其起始地址标识。
p+1 不在该列表中,因此 free 会找到一个块来释放,并且不会执行任何操作。
in standardese this behavior is "undefined", but actually, nothing will get freed.
the reason is that what malloc does it keep a list of the chunks it had allocated, each chunk is identified by its starting address.
p+1 is not on that list, so free will find a chunk to free, and will do nothing.