在“Inside the C++ Object Model”一书的第 6.3 节中,临时对象(第 230 页):
The actual results are implementation dependent based on how aggressive the underlying delete operator is in actually freeing the memory addressed. Some implementations, while marking the memory as free, do not actually alter it in any way. Until the memory is claimed by something else, it can be used as if it had not been deleted. While obviously not an exemplary approach to software engineering, this idiom of accessing memory after it has been freed is not uncommon. Many implementations of
malloc()
, in fact, provide a special invocationmalloc(0);
to guarantee just this behavior.
根据上面的说法,malloc(0)
似乎与访问已经被释放的内存(但其内容没有改变)有关。
我的问题是 malloc(0)
如何保证这种行为?
最佳答案
编辑:我没有注意到“C++ 对象模型内部”是一个引用,而不仅仅是问题标题的一部分。
正如 Dietmar Kuhl 所说,它看起来像一个杂物,即使它出现在你的平台上,你也不应该依赖这样的扩展。
“大多数平台”做包括某种malloc
调试工具来帮助程序员找到访问已经传递给free
的内存的代码。这可能涉及不那么懒惰地执行内存管理或使用特殊字节模式覆盖。听起来该文本将 malloc(0)
描述为禁用此类工具的一种方式。在 Mac OS X 上,我记得有一个环境变量(类似于 MALLOC_DEBUG
)可以控制它。该工具的功能和启用方式在平台之间会有很大的差异。覆盖 malloc(0)
既不常见也不是好的接口(interface)。
编辑:我在 Inside the C++ object model 中找到它斯坦利·利普曼(Stanley Lippman),1996 年。不是权威来源。整个页面似乎都致力于讨论标准和“准标准”平台实现之间的差异,尽管 1996 年也是在第一个标准完成之前。请注意,这是很久很久以前的计算机时代,除非您将特定的应用程序从死里复活,否则这些信息将完全无关紧要。 Lippman 显然发布了一本关于 C++11 的新书,其中包括具有多线程支持的更新对象模型。 (虽然我不知道他或者那本书好不好。)
关于c++ - 为什么 malloc(0) 在 "Inside the C++ Object Model?"有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14027448/