如何“释放/删除”?工作?

发布于 2024-11-16 15:50:04 字数 484 浏览 9 评论 0原文

可能的重复:
删除在 C++ 中如何工作?
C 编程:free 如何知道要释放多少?

对于每个动态内存分配,使用“malloc/new”,我们有方法“free/delete”来释放分配的内存。

我的问题是,如果内存分配大小是在运行时决定的并且内存位置不连续,这些内存释放方法如何知道要释放多少内存以及要清除的内存位置是什么?

如果我们只向它们传递一个指向单个位置的指针,那么是什么让这些函数起作用?

Possible Duplicates:
How does delete work in C++?
C programming : How does free know how much to free?

For every dynamic memory allocation, using 'malloc / new', we have methods, 'free / delete' to free the allocated memory.

My question is if the memory allocation size is decieded at runtime and the memory locations not being contiguous, how does these memory freeing methods know how much memory to free and what are the memory locations to be cleared ?

What makes these functions work if we are passing them only a pointer to single location ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

南城旧梦 2024-11-23 15:50:04

它们会跟踪您在内部分配了多少内存。

They keep track of how much memory you've allocated where internally.

花辞树 2024-11-23 15:50:04

当 malloc/new 分配内存时,它还会记录为指向给定内存位置的指针分配的内存位置和数量。当您给它一个指针时,free/delete 查找要释放的内存。

这就是为什么你永远不应该尝试释放用“+=”或类似的东西移动的指针。

When malloc/new allocates memory it also records where and how much memory it allocated for a pointer to a given memory location. free/delete looks up what memory to deallocate when you give it a pointer.

That is why you should never try to free a pointer that you moved with "+=" or something like that.

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