我可以通过引用偏移指针来 free() 吗?
我正在使用 malloc()
在堆上分配一些内存。我向指针添加偏移量并将其返回给调用函数 return ptr+(sizeof(char)*4))
,其中此返回值存储在 ptrReturned
中, 例如。
最大的问题是,当我free(ptrReturned)
(从分配块的开头偏移sizeof(char)*4
)时,整个块是否会被释放或者它会释放从偏移量到分配块末尾的内存吗?我使用的编译器是MSVC++2008。
如果分配的地址存储在链表中,并且有指向前一项的指针,那么它应该释放从前一个指针为 NULL 到下一个指针为 NULL 的整个块,对吗?
我尝试过调试和观察内存,但无法让它覆盖释放的块空间。有没有一种方法可以显式地尝试在堆上的定义地址分配空间,并且可能会因尝试分配已分配的内存而出现异常?这样我就能知道,当然,是否没有更简单的答案。
我希望问题很清楚,如果我遗漏了一些信息,请在评论中告诉我。谢谢。
Possible Duplicate:
Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior?
I'm allocating some memory on the heap using malloc()
. I'm adding an offset to the pointer and returning it to a calling function return ptr+(sizeof(char)*4))
, where this return value is stored in ptrReturned
, for example.
The big question is, when I free(ptrReturned)
, which is offset from the beginning of the allocated block by sizeof(char)*4
, will the whole block be freed or will it free memory from the offset up to the end of the allocated block? The compiler I'm using is MSVC++2008.
If the allocated addresses are stored in a linked list, and there are pointers to previous items, then it should free the whole block from where previous pointer is NULL up to where next pointer is NULL, right?
I've tried debugging and watching the memory, but I can't get it to overwrite the freed up block space. Is there a way to maybe explicitly try and allocate space on the heap at a defined address, and maybe get an exception from trying to allocate already allocated memory? That way I'll be able to know, if there is, of course, no simpler answer.
I hope the question is clear, if I'm missing on some information, please let me know in the comments. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将与 malloc() 返回的相同指针值传递给 free(),否则您的程序将出现未定义的行为。您认为它可能会释放全部或部分分配块的期望是没有根据的。
You must pass in the same pointer value to free() that was returned by malloc(), or your program will have undefined behaviour. Your expectation that it might free all or part of the allocated block is unfounded.
我从标准中找到了以下引用:
I found the following quote from the standard: