一道面試題: 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
