一道面试题: C能申请的最大全局数组大小?

一道面试题: C能申请的最大全局数组大小?
第一反应好像是4GB,但明显不对,代码和数据都要占空间,肯定到不了4GB。但是又想内存可以和硬盘数据交换,那到底是多少?
应该是32位系统是理论上不能超过4GB(因为地址宽度4bytes,寻址的限制),实际中由于OS实现的细节会更少(比如Linux 1GB给了内核),而64位系统不超过2^64-1;内存大小最好大于数组长度,否则导致和磁盘交换数据,性能下降
如果是局部变量,分配在栈上,空间会更小,取决于编译器

参考:
http://stackoverflow.com/questions/9386979/the-maximum-size-of-an-array-in-c

在C中并没有规定固定的数组大小限制;
单个对象的大小或者数组的大小取决于 SIZE_MAX,SIZE_MAX 也是size_t的最大值,size_t 是 sizeof的返回类型
SIZE_MAX 取决于实现
cout<<SIZE_MAX ; 输出 4294967295 = 2^32-1;
而指针类型void * 的宽度(可以指向某个对象或数组元素的地址), 决定了程序中所有对象可能的上界
C规定了 void * 的下界,却没有规定上界
a conforming implementation could have SIZE_MAX equal to 2^1024-1

然而在gcc中声明全局 unsigned char arr[SIZE_MAX]; 却不能通过编译:error: size of array 'arr' is too large
VS 中一样: error C2148: 数组的总大小不得超过 0x7fffffff 字节

如果是分配在堆上,不能超过1M
和windows的内存管理有关系,windows的4G空间分成两部分,低2G的部分给用户,高2G的部分保留给系统。但2G很早就不够用,所以对于32位的系统,可以用 4-gigabyte tunine ,将进程使用部分扩大至3G,但不论如何,不能超过4G
解决办法就是编译成64位应用程序

g++ 加上 -m64 参数编译:
main.cpp:1:0: sorry, unimplemented: 64-bit mode not compiled in /*
应该是要用64位的mingw才行;

------

By static array, I assume, you mean a fixed length array (statically allocated, like int array[SIZE], not dynamically allocated). Array size limit should depend on the scope of the array declared.

If you have declared the array in local scope (inside some routine), size limit is determined by stack size.
If gcc is running on linux, the stack size is determined by some environment variable. Use ulimit -a to view and ulimit -s STACK_SIZE to modify the stack size.
If gcc is running on windows (like MinGW), stack size can be specified by gcc -Wl,--stack, STACK_SIZE.
If you have declared the array in global scope, the array is stored in DATA or BSS section (based on whether the array is initialized or uninitialized respectively). The DATA and BSS section size are determined by underlying OS.
If you have declared the array in static scope (like static int array[SIZE]), again, the array is stored in DATA or BSS section (based on whether the array is initialized or uninitialized respectively). The DATA and BSS section size are determined by underlying OS.
------
64位系统,windows用户地址空间8TB, linux 是 128TB; on Windows (except for Windows 8.1), the user-mode address space for applications in 8 TB. On Linux, the limit is usually 128 TB. The processor hardware may also introduce a limitation (e.g., restricting addresses to 48 bits, or 256 TB).
https://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details

 

posted @ 2015-11-02 21:52  tofixer  阅读(5199)  评论(0编辑  收藏  举报