c ++动态内存分配限制 [英] c++ dynamic memory allocation limit

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

问题描述

在C ++中使用new或malloc动态分配是否存在某种限制(系统限制或其他限制)? 该系统是64位的,我想分配一个约8亿个结构的数组.

Is there any kind of limit, system or otherwise, for dynamic allocation with new or malloc in C++? The system is 64bit and I want to allocate an array of some ~800million structs.

之所以没有自己进行测试,是因为我目前无法访问具有足够内存的计算机,因此我觉得在我的当前计算机上进行测试是没有意义的.

The reason I didn't test it on my own before was because I don't currently have access to a machine with enough memory, so I felt that there was no point testing it on my current machine.

运行自己的测试后,我可以分配8亿个元素,但是一旦达到8.5亿个,malloc就会返回NULL.该结构包含7个浮点数,因此总大小约为22GB. 这个看似随意的限制背后的原因是什么?这台机器有4GB的ram和4GB的虚拟内存,所以我不确定为什么我还能分配那么多.

After running my own tests, I can allocate 800million elements fine, but malloc returns NULL once I hit ~850million. The struct contains 7 floats, so the total size is about 22GB. What's the reason behind this seemingly arbitrary limit? This machine has 4GB of ram and 4GB virtual memory, so I'm not sure why I'm even able to allocate that much.

推荐答案

限制大约是您的可用内存加上交换到磁盘所允许的空间. 对于创纪录的8亿字节= 800 Mb,因此您可以安全地坐在小结构上,甚至不需要交换(并且应避免使用) 只需尝试一下,看看它在哪里崩溃;-)

The limit is approximately your free ram plus the space allowed for swapping to disk. For the record 800 million byte = 800 Mb so you might sit well on the safe side with small structs, even swapping might not be required (and should be avoided) Just try it out and see where it crashes ;-)

64位:2 ^ 64/2 ^ 30 =大约17 *10⁹千兆字节(对于可字节寻址的体系结构,1Gb = 2 ^ 30 Bit),因此这里无后顾之忧

64 Bit: 2^64/2^30 = approx. 17* 10⁹ Gigabyte (for a byte addressable architecture, 1Gb=2^30 Bit) so no worries here

32位:2 ^ 32 =大约4 GB,因此即使在这里您也可以处于安全状态

32 Bit: 2^32 = approx 4 Gigabyte so even here you could be on the safe side

除以2以获得带符号的值,至少在64位系统上仍然有很大的空间

Divide by two for signed values, still you have much room left at least on a 64bit system

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

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