如何delete []知道数组的大小? [英] How does delete[] know the size of an array?

查看:104
本文介绍了如何delete []知道数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:



delete []如何知道操作数数组的大小?

复制 http://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array

我很好奇如何delete []计算出分配的内存的大小。当我做类似的事情:

I am curious how delete[] figures out the size of the allocated memory. When I do something like:

int* table = new int[5];
delete[] table;



我理解表的内存被释放。但是,如果我将指针重新分配到一些不同的表会发生什么。

I understand that the memory of the table is freed. But what would happen if I reassigned the pointer to some different table.

int* table = new [5];
int* table2 = new [9];
table = table2;
delete[] table;

我会获得5或9号的桌子吗?我感兴趣的是如何新的[]和删除[]分享关于他们的大小的信息。

Will I free a table of the size 5 or 9? I am interested in how new[] and delete[] share information about their size. Or maybe I am missing something essential here.

推荐答案

它会删除大小为9的数组。
删除

It would delete an array of size 9. It deletes the array pointed to by the pointer.

这是未指定大小信息的存储方式,因此每个编译器可能以不同的方式实现它,但是一个通用的方式是在数组之前分配一个额外的块。也就是说,当你这样做:

It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this:

int* table = new int[5];

它实际上分配了一个6个整数的数组,并将数组大小存储在第一个元素中。然后它返回一个指向第二个元素的指针。所以要找到大小,删除[]只需要读表[-1],基本上。

it actually allocates an array of 6 integers, and stores the array size in the first element. Then it returns a pointer to the second element. So to find the size, delete[] just has to read table[-1], basically.

这是一个常见的方法,但语言标准doesn' t指定必须以此方式完成。

That's one common way to do it, but the language standard doesn't specify that it must be done in this way. Just that it has to work.

另一种方法可能是使用数组的地址作为密钥进入某些全局散列表。任何方法都有效,只要它产生正确的结果。

Another approach might be to use the address of the array as a key into some global hash table. Any method is valid, as long as it produces the correct results.

这篇关于如何delete []知道数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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