且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态分配数组大小

更新时间:2023-02-11 17:25:07

实际上,内存分配器的典型实现也存储了一些其他信息.

In actual fact, the typical implementation of the memory allocators store some other information too.

没有访问此信息的标准方法,实际上,标准中没有说明存储什么信息的信息(以字节为单位的大小,元素数及其大小,指向最后一个元素的指针等).

There is no standard way to access this information, in fact there is nothing in the standard saying WHAT information is stored either (the size in bytes, number of elements and their size, a pointer to the last element, etc).

如果您具有对象的基址和正确的类型,我怀疑可以相对容易地找到分配的大小(不一定不花钱").但是,有几个问题:

If you have the base-address of the object and the correct type, I suspect the size of the allocation could be relatively easily found (not necessarily "at no cost at all"). However, there are several problems:

  1. 假定您具有原始指针.
  2. 假定使用该运行时库的分配代码完全分配了内存.
  3. 假定分配器未以某种方式舍入"分配地址.

为说明这可能会出错的方法,我们可以这样做:

To illustrate how this could go wrong, let's say we do this:

size_t get_len_array(int *mem)
{
   return allcoated_length(mem);
}

... 
void func()
{
    int *p = new int[100];
    cout << get_len_array(p); 
    delete [] p;
}

void func2()
{
    int buf[100];
    cout << get_len_array(buf); // Ouch!
}