据我了解,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 ofdelete[]
?"
对于通过 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 thecalloc()
,malloc()
,posix_memalign()
,realloc()
, orstrdup()
function, or if the space has been deallocated by a call to free() orrealloc()
, 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 而言标记应用于您的(原始)问题,因为 c 不支持 delete
或 new
要求这个 c 语言是毫无用处的。
关于c++ - 使用 free() 释放 new 分配的内存空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174631/