我可以通过引用偏移指针来 free() 吗?

发布于 2024-10-12 15:17:24 字数 752 浏览 6 评论 0原文

可能的重复:
是否传递给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗笺 2024-10-19 15:17:24

您必须将与 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.

忆梦 2024-10-19 15:17:24

我从标准中找到了以下引用:

否则,如果参数不
匹配之前返回的指针
calloc、malloc 或 realloc
功能,或者如果空间已
通过调用 free 或
realloc,行为未定义。

I found the following quote from the standard:

Otherwise, if the argument does not
match a pointer earlier returned by
the calloc, malloc, or realloc
function, or if the space has been
deallocated by a call to free or
realloc, the behavior is undefined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文