加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:47:13 所属栏目:百科 来源:网络整理
导读:在“The C Programming Language”一书中,Stroustrup说: “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 impleme
在“The C Programming Language”一书中,Stroustrup说:

“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分配的每个对象的大小都位于堆中的某个位置.位置是否已知,是否可以访问它?

解决方法

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

没有标准的方法来访问这些信息,实际上标准中没有任何内容表示存储了什么信息(字节大小,元素数量及其大小,指向最后一个元素的指针等).

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

>它假设您有原始指针.
>它假定内存与运行时库的分配代码完全分配.
>它假设分配器不以某种方式“舍入”分配地址.

为了说明这可能出错,让我们说这样做:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读