tet*_*s11 2 c++ memory memory-management
我有以下代码:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef uint64_t Huge_num; // 8 bytes
typedef Huge_num * Huge_Arr; // Array of 8 byte elements
using namespace std;
// Function: Return a huge array
static Huge_Arr* requestMem(int n)
{
cout << "requesting :"
<< (sizeof(Huge_num)*n)/(1024*1024*1024)
<< "GB" << endl;
Huge_Arr *buff;
try {
buff = new Huge_Arr[n];
}
catch (bad_alloc){
cout << "Not enough mem!" << endl;
exit(-1);
}
return buff;
}
// Main
int main(){
for (int i=1; i< 10; i++){
Huge_Arr *mem = requestMem(i*90000000);
delete mem;
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,malloc在抛出bad_alloc()
错误之前只能抓取不超过2GB的内存.
据我所知,在32位系统上,最大地址空间确实在2GB的相同数量级.
但我正在使用Ubuntu 12.04 x86_64,它应该能够处理更大的内存请求,对吗?
编辑:结果是答案是我正在编译g++ -std=c00x
,这是32位?不确定,无论哪种方式我改变Makefile删除-std
标志,它编译得很好
malloc
正在分配连续的内存.您获得badalloc
2 GB内存请求的事实并不一定意味着您的可用内存少于2 GB,这也意味着可用内存碎片化.如果要测试可在系统上分配的内存量,请尝试分配较小的块.