指针运算后释放指针
我的问题很简单。假设我们有:
char* ptr = (char*) malloc(sizeof(char)*SIZE);
ptr+= SIZE/2;
free(ptr);
当我们释放指针时会发生什么?是未定义的操作吗? 它是释放所有 SIZE 缓冲区还是仅释放剩余的 SIZE/2? 预先感谢您为我消除了歧义。
My question is very simple one. Say we have:
char* ptr = (char*) malloc(sizeof(char)*SIZE);
ptr+= SIZE/2;
free(ptr);
What happens when we free the pointer? Is it undefined operation?
Does it free all of SIZE buffer or only the remaining SIZE/2?
Thanks in advance for disambiguating this for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的程序可能会崩溃:free() 操作在 C 语言中实际上非常简单,但仅适用于原始分配的地址。
典型的内存分配器的工作原理如下伪代码:
因此当您调用 free(ptr) 时,分配器会在指针之前移动 6 个字节来检查签名。如果找不到签名,就会崩溃:)
Your program will probably crash: the free() operation is actually quite simple in C, but works only on the original allocated address.
The typical memory allocator works like this pseudo code:
So when you call
free(ptr)
, the allocator goes 6 bytes before your pointer to check for the signature. If it doesn't find the signature, it crashes :)如果
free()
的参数与之前通过malloc()
及其友元分配的指针不匹配,则行为未定义。您很可能会在您的libc
版本中遇到分段错误或断言失败。题外话:最好不要在 C 中转换
malloc()
的结果。If the argument to
free()
does not match a pointer previously allocated by means ofmalloc()
and friends, the behaviour is undefined. You will most likely encounter a segmentation fault or a failed assertion in your version oflibc
.Offtopic: it's better you didn't cast the result of
malloc()
in C.该行为是未定义的,很可能会导致分段错误 - 这是好的情况。在最坏的情况下,它会破坏程序的内存并引发各种奇怪的错误和错误的输出。
The behavior is undefined and will most likely result in a segmentation fault - and that's the good case. In the worst case, it will corrupt your program's memory and induce all kind of weird bugs and wrong outputs.
在大多数实现中,这应该会导致某种致命错误。您只能释放已分配缓冲区的开头部分。
在 Windows(使用 Visual Studio 编译器)上遇到的典型错误类似于“不是有效的堆指针”。在 Linux 上,正如上面 phihag 所说,它通常会导致分段错误。在这两种情况下,都是运行时错误,通常会终止程序的执行。
On most implementations this should result in some sort of fatal error. You can only free the begining of an allocated buffer.
They typical error you would get on windows (with the visual studio compilers) would be something like "not a valid heap pointer". On linux, as said above by phihag, it would usually result in a segmentation fault. In both cases, it is a runtime error that would usually terminate the execution of the program.
该行为是未定义的。我猜你会遇到段错误......这就是我在我的系统中尝试时遇到的情况。
free()
要求调用者传递由内存分配器函数(如malloc()
)返回的地址。其他任何事情都会导致未定义的行为。The behaviour is undefined. I guess you'd get a segfault ... that's what I got when I tried in my system.
free()
requires the caller to pass an address that was returned by a memory allocator function likemalloc()
. Anything else results in undefined behaviour.