由new分配的free()内存安全吗? [英] 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或realloc]分配的内存块,则会导致未定义的行为.
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
和 free
与 new
混合和匹配>和 delete
草案,C ++标准为此参考了C99标准,如果我们转到
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
分配的内容使用 free
的任何状态.因此,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或realloc释放了空间,则行为未定义>.
这篇关于由new分配的free()内存安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!