c++ - 使用 free() 释放 new 分配的内存空间

标签 c++ free dynamic-memory-allocation

据我了解,delete[]用于释放new分配的内存空间。 free() 也可用于释放该内存空间。那么,当使用 free() 代替 delete[] 释放内存时,我会遇到哪些类型的问题?

最佳答案

"free() can also be used to release that memory space."

不可以,free() 不能用于释放通过 new()new[] 分配的内存。

"So which type of problems will I have to face when releasing memory using free() in place of delete[]?"

对于通过 new[] 分配的内存,使用 free() 而不是 delete[]未定义行为 (除了复杂对象的析构函数不会被调用),这可能会导致运行时异常。

来自POSIX compliant reference (强调我的):

The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), or strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Any use of a pointer that refers to freed space results in undefined behavior.

嗯,new[]new() 的某些实现可能依赖于 malloc() 函数系列,而其他实现可能不会。所以你不能肯定地说分配的内存指针可以安全地与 free 一起使用(即使你不关心析构函数调用问题)。


结论:

delete[] 的使用仅明确定义为对使用 new[] 分配的内存进行操作,delete 对应于以下结果

此外,free() 的使用也只能与使用 malloc() 函数系列分配的内存一起明确定义。


而言标记应用于您的(原始)问题,因为 c 不支持 deletenew 要求这个 c 语言是毫无用处的。

关于c++ - 使用 free() 释放 new 分配的内存空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174631/

相关文章:

C++ 子结构

c - 不确定是否为结构分配内存

c - free(ptr) 有时会崩溃,指针始终有效

c - 改进我执行 malloc 和 free 的方式

c - 打印从包含特定单词的文件中读取的一行

java - 了解 Java 中的对象分配

c++ - 用动态数组模拟的单链表

c++ - 错误 : expected unqualified-id before ‘)’ token Node()

c++ - 结构的前向声明不起作用 - 无法弄清楚为什么

python - 如何在python脚本中控制windows master音频