gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:14:28 25 4
gpt4 key购买 nike

据我了解,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[]?"

使用 free() 而不是 delete[] 分配给 new[] 的内存是未定义的行为 (除了不会调用复杂对象的析构函数),这样可能会以运行时异常结束。

来自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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com