调用 free() 或 delete 而不是 delete[] 有什么危险吗?

2021-12-24 00:00:00 memory-management c++ new-operator free

可能的重复:
(POD)释放内存:delete[]等于delete吗?

delete 是否会释放数组中第一个元素之外的元素?

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

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

在上述情况下是否重要,因为 s 的所有元素都是连续分配的,并且应该不可能删除 仅数组的一部分?

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.

对于原始类型,如charint,有什么区别:

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

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

除了各个调用通过 delete->free 释放机制所采用的路由?

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.

相关文章