当我想在堆栈上分配8mb时,为什么分段错误

Suk*_*lay 1 c++ linux stack

当我想分配这个数组并输出第一个元素时,我得到了分段错误.我知道这个元素没有初始化,但为什么分段错误?码:

#include <iostream>

using namespace std;

int main() {
    unsigned long long adj[1024][1024];
    cout << adj[0][0];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在OSX上测试(1GB可用内存)和Ubuntu 12.04(大约15gb可用内存).

PS:我确信在linux中我们可以在堆栈上分配大数组.

编译器试过:

OSX(clang++, g++4.8.3 -std=g++11), Ubuntu(g++4.8.1)
Run Code Online (Sandbox Code Playgroud)

错误:

OSX:

Segmentation fault: 11
Run Code Online (Sandbox Code Playgroud)

UBUNTU:分段错误

qeh*_*hgt 7

Ubuntu的默认安装对用户空间进程有这个限制:

$ ulimit -a
-t: cpu time (seconds)              unlimited
-f: file size (blocks)              unlimited
-d: data seg size (kbytes)          unlimited
-s: stack size (kbytes)             8192
-c: core file size (blocks)         0
-m: resident set size (kbytes)      unlimited
-u: processes                       16072
-n: file descriptors                1024
-l: locked-in-memory size (kbytes)  64
-v: address space (kbytes)          unlimited
-x: file locks                      unlimited
-i: pending signals                 16072
-q: bytes in POSIX msg queues       819200
-e: max nice                        0
-r: max rt priority                 0
-N 15:                              unlimited
Run Code Online (Sandbox Code Playgroud)

因此,堆栈大小限制为8192 KB.你的程序需要更多,所以OS就是杀了它.

尝试为您的adj阵列使用动态分配,或者(不推荐)通过ulimit -s 32768命令增加限制.