“free”是安全的吗?由`new'分配的内存? [英] Is it safe to `free()` memory allocated by `new`?
问题描述
我正在处理一个C ++库,其中的一个函数返回一个(新分配)指针到一个双精度数组。 API声明调用者负责释放内存。
I'm working on a C++ library, one of whose functions returns a (freshly allocated) pointer to an array of doubles. The API states that it is the responsibility of the caller to deallocate the memory.
但是,C ++库曾经在C中实现,并且该函数分配内存与 malloc()
。它还假设调用者将用 free()
释放该内存。
However, that C++ library used to be implemented in C and the function in question allocates the memory with malloc()
. It also assumes that the caller will deallocate that memory with free()
.
我可以安全地替换调用 malloc()
调用 new
?将现有的客户端代码(使用 free()
断开如果我这样做?迄今为止我可以找到的是 free
,其中指出
Can I safely replace the call to malloc()
with a call to new
? Will the existing client code (that uses free()
break if I do so? All I could find so far was the official documentation of free()
, which states that
如果ptr没有指向分配有[malloc,calloc
If ptr does not point to a block of memory allocated with [malloc, calloc or realloc], it causes undefined behavior.
但我相信这是在C ++自带的分配操作符之前编写的。
But I believe this was written before C++ came along with its own allocation operators.
推荐答案
您不能混合搭配 malloc
和免费
与新
和删除
草案C ++标准回到C99标准如果我们转到 C ++标准草案 20.6.13 C库(强调我的未来):
You are not allowed to mix and match malloc
and free
with new
and delete
the draft C++ standard refers back to the C99 standard for this and if we go to the draft C++ standard section 20.6.13
C library it says (emphasis mine going forward):
内容与标准C库标头stdlib.h相同,但有以下更改:
The contents are the same as the Standard C library header stdlib.h, with the following changes:
和:
函数calloc(),malloc()和realloc尝试通过调用:: operator
new()(18.6)分配存储。
The functions calloc(), malloc(), and realloc() do not attempt to allocate storage by calling ::operator new() (18.6).
和:
函数free()不会通过调用:: operator delete()来释放存储空间。
另请参见:ISO C条款7.11.2。
The function free() does not attempt to deallocate storage by calling ::operator delete(). See also: ISO C Clause 7.11.2.
并包括其他更改,分配给 new
的内容免费
。因此,C99标准草案中的 7.20.3.2
部分的自由功能仍然是正确的参考,它说:
and includes other changes, none of which state that we can use free
on contents allocated with new
. So section 7.20.3.2
The free function from the draft C99 standard is still the proper reference and it says:
否则,如果参数与calloc,malloc或realloc函数先前返回的指针不匹配,或者如果空间已被释放或重新分配,行为未定义。
这篇关于“free”是安全的吗?由`new'分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!