gpt4 book ai didi

c++ - 获取动态分配的数组大小

转载 作者:太空狗 更新时间:2023-10-29 20:13:59 26 4
gpt4 key购买 nike

Stroustrup 在“The C++ Programming Language”一书中说:

"To deallocate space allocated by new, delete and delete[] must be able to determine the size of the object allocated. This implies that an object allocated using the standard implementation of new will occupy slightly more space than a static object. Typically, one word is used to hold the object’s size.

这意味着 new 分配的每个对象都有其大小位于堆中的某处。该位置是否已知?如果已知,我该如何访问?

最佳答案

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

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

编辑:如果您有对象的基地址和正确的类型,我怀疑分配的大小可以相对容易地找到(不一定“完全免费”)。但是,存在几个问题:

  1. 它假定您有原始指针。
  2. 它假定内存是根据运行时库的分配代码分配的。
  3. 它假定分配器不会以某种方式“舍入”分配地址。

为了说明这可能会出错,假设我们这样做:

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!
}

关于c++ - 获取动态分配的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578643/

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