C ++为变量分配异常大的amout内存 [英] C++ allocates abnormally large amout memory for variables

查看:141
本文介绍了C ++为变量分配异常大的amout内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近得知一个整数需要4个字节的内存。

I recently got to know an integer takes 4 bytes from the memory.

首先运行此代码,并测量内存使用情况:

First ran this code, and measured the memory usage:

int main()
{
   int *pointer;
}


  • 需要144KB。 >

然后我修改代码以分配 1000个整数变量

Then I modified the code to allocate 1000 integer variables.

int main()
{
   int *pointer;

   for (int n=0; n < 1000; n++)
     { 
       pointer = new int ; 
     }
}


  • 144 =)24KB

    ,但假设要占用1000个整数(4bytes x 1000 =)3.9KB 。 b $ b
  • Then it took (168-144=) 24KB
    but 1000 integers are suppose to occupy (4bytes x 1000=) 3.9KB.

然后我决定使用 262,144个整数变量,这些变量应该消耗1MB的内存

int main()
{
   int *pointer;

   for (int n=0; n < 262144; n++)
     { 
       pointer = new int ; 
     }
}

令人惊讶的是, strong>

Surprisingly, now it takes 8MB

>

内存使用量相对于整数数量呈指数增长。

为什么会发生这种情况?

Memory usage, exponentially grows respective to the number of integers.
Why is this happening?

我在Kubuntu 13.04(amd64)

请给我一点解释。
感谢!

I'm on Kubuntu 13.04 (amd64)
Please give me a little explanation. Thanks!

注意: sizeof(integer)返回 4

NOTE: sizeof(integer) returns 4

推荐答案

单独分配的动态对象的内存不需要是连续的。事实上,由于 new char [N] (即在 alignof(std :: maxalign_t) $ c>,通常是16),标准内存分配器可能永远不会返回任何 16字节对齐的内存。因此每个 int 分配实际上消耗(至少)16个字节。 (分配器可能需要进一步的内存用于内部记账。)

Memory for individually allocated dynamic objects is not required to be contiguous. In fact, due to the alignment requirements for new char[N] (namely to be aligned at alignof(std::maxalign_t), which is usually 16), the standard memory allocator might just never bother to return anything but 16-byte aligned memory. So each int allocation actually consumes (at least) 16 bytes. (And further memory may be required by the allocator for internal bookkeeping.)

道德当然是你应该使用 std :: vector< ; int>(1000000)来获取一百万个动态整数的合理句柄。

The moral is of course that you should be using std::vector<int>(1000000) to get a sensible handle on one million dynamic integers.

这篇关于C ++为变量分配异常大的amout内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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