free()之后内存会发生什么?
我知道在你的硬盘上,如果你删除一个文件,数据并不会(立即)消失。数据仍然存在,直到被覆盖。我想知道记忆中是否存在类似的概念。假设我为一个字符串分配了 256 个字节,在我 free()
直到它被覆盖之后,该字符串是否仍然漂浮在内存中的某个地方?
I know that on your hard drive, if you delete a file, the data is not (instantly) gone. The data is still there until it is overwritten. I was wondering if a similar concept existed in memory. Say I allocate 256 bytes for a string, is that string still floating in memory somewhere after I free()
it until it is overwritten?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的比喻是正确的。内存中的数据不会消失或类似的情况;尽管尝试从释放的内存中读取是未定义的行为,但在 free() 之后这些值确实可能仍然存在。
Your analogy is correct. The data in memory doesn't disappear or anything like that; the values may indeed still be there after a
free()
, though attempting to read from freed memory is undefined behaviour.一般来说,它确实会保留下来,除非您在
释放
之前显式覆盖该字符串(就像人们有时对密码所做的那样)。某些库实现会自动覆盖已释放的内存以捕获对其的访问,但这不是在释放模式下完成的。Generally, it does stay around, unless you explicitly overwrite the string before
free
ing it (like people sometimes do with passwords). Some library implementations automatically overwrite deallocated memory to catch accesses to it, but that is not done in release mode.答案很大程度上取决于实施。在良好的实现中,内存的至少开头(或结尾?)可能会被簿记信息覆盖,以跟踪稍后可以重用的空闲内存块。但细节会有所不同。如果您的程序具有任何级别的并发/线程(即使在您可能看不到的库实现中),那么此类内存可能会被异步破坏,甚至可能以甚至读取它都是危险的方式。当然,
free
的实现可能会完全取消程序虚拟地址空间中的地址范围的映射,在这种情况下,尝试对其执行任何操作都会使程序崩溃。从应用程序作者的角度来看,您应该根据规范简单地对待
free
,并且永远不要访问已释放的内存。但从系统实现者或集成者的角度来看,了解(或设计)实现可能很有用,在这种情况下,您的问题就很有趣。The answer depends highly on the implementation. On a good implementation, it's likely that at least the beginning (or the end?) of the memory will be overwritten with bookkeeping information for tracking free chunks of memory that could later be reused. However the details will vary. If your program has any level of concurrency/threads (even in the library implementation you might not see), then such memory could be clobbered asynchronously, perhaps even in such a way that even reading it is dangerous. And of course the implementation of
free
might completely unmap the address range from the program's virtual address space, in which case attempting to do anything with it will crash your program.From a standpoint of an application author, you should simply treat
free
according to the specification and never access freed memory. But from the standpoint of a systems implementor or integrator, it might be useful to know (or design) the implementation, in which case your question is then interesting.如果您想验证您的实现的行为,下面的简单程序将为您做到这一点。
If you want to verify the behaviour for your implementation, the simple program below will do that for you.