在调用free()或delete而不是delete []时有什么危险吗? [英] Is there any danger in calling free() or delete instead of delete[]?

查看:161
本文介绍了在调用free()或delete而不是delete []时有什么危险吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

(POD)释放内存:delete []等于删除?

delete 是否可以解除数组中第一个元素之外的元素?

Does delete deallocate the elements beyond the first in an array?

char *s = new char[n];
delete s;

在上述情况下,看到 s 是连续分配的,并且不应该 delete 只有数组的一部分?

Does it matter in the above case seeing as all the elements of s are allocated contiguously, and it shouldn't be possible to delete only a portion of the array?

对于更复杂的类型, delete 调用超出第一个对象的析构函数?

For more complex types, would delete call the destructor of objects beyond the first one?

Object *p = new Object[n];
delete p;

如何 delete [] Object 超过第一个,是不是意味着它必须知道分配的内存区域的大小?如果由于性能原因,内存区域被分配了一些悬挂会怎么样?例如,可以假设不是所有分配器都将提供单个字节的粒度。

How can delete[] deduce the number of Objects beyond the first, wouldn't this mean it must know the size of the allocated memory region? What if the memory region was allocated with some overhang for performance reasons? For example one could assume that not all allocators would provide a granularity of a single byte. Then any particular allocation could exceed the required size for each element by a whole element or more.

对于原始类型,例如 char int 之间是否有任何差异:

For primitive types, such as char, int, is there any difference between:

int *p = new int[n];
delete p;
delete[] p;
free p;

除了通过 delete - >

Except for the routes taken by the respective calls through the delete->free deallocation machinery?

推荐答案

行为(很可能会损坏堆或程序立即崩溃),你不应该做它。只有具有对应于用于分配该存储器的原始性的可用存储器。

It's undefined behaviour (most likely will corrupt heap or crash the program immediately) and you should never do it. Only free memory with a primitive corresponding to the one used to allocate that memory.

违反这个规则可能导致巧合的正常运行,但是程序可以破坏一旦任何东西更改 - 编译器,运行时,编译器设置。

Violating this rule may lead to proper functioning by coincidence, but the program can break once anything is changed - the compiler, the runtime, the compiler settings. You should never rely on such proper functioning and expect it.

delete [] 使用特定于编译器的服务数据确定元素的数量。通常,当调用 new [] 时,分配一个更大的块,该数字存储在开头,呼叫者被赋予存储号码后面的地址。无论如何 delete [] 依赖于由 new [] 分配的块,而不是任何其他。如果除了 new [] delete [] 之间配对任何东西,反之亦然,你会遇到未定义的行为。

delete[] uses compiler-specific service data for determining the number of elements. Usually a bigger block is allocated when new[] is called, the number is stored at the beginning and the caller is given the address behind the stored number. Anyway delete[] relies on the block being allocated by new[], not anything else. If you pair anything except new[] with delete[] or vice versa you run into undefined behaviour.

这篇关于在调用free()或delete而不是delete []时有什么危险吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆