动态分配数组大小 [英] Getting dynamically allocated array size

查看:114
本文介绍了动态分配数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在"C ++编程语言"一书中,Stroustrup说:

In "The C++ Programming Language" book Stroustrup says:

"要解除分配由 new 分配的空间,删除 delete [] 必须能够确定分配的对象的大小.意味着使用 new 的标准实现分配的对象将比静态对象占用更多的空间.通常,一个单词用于保存对象的大小.

"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分配的每个对象的大小都位于堆中的某个位置.是否知道该位置,并且该如何访问?

That means every object allocated by new has its size located somewhere in the heap. Is the location known and if it is how can I access it?

推荐答案

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

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

这篇关于动态分配数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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