c++ - 为什么当我想在堆栈上分配 8mb 时出现段错误

标签 c++ linux stack

<分区>

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

#include <iostream>

using namespace std;

int main() {
    unsigned long long adj[1024][1024];
    cout << adj[0][0];
    return 0;
}

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

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

编译器尝试过:

OSX(clang++, g++4.8.3 -std=g++11), Ubuntu(g++4.8.1)

错误:

操作系统:

Segmentation fault: 11

优本图: 段错误

最佳答案

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

因此,堆栈大小限制为 8192 KB。你的程序需要更多,所以操作系统会干掉它。

尝试为您的 adj 数组使用动态分配或(不推荐)通过 ulimit -s 32768 命令增加限制。

关于c++ - 为什么当我想在堆栈上分配 8mb 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23999251/

相关文章:

linux - 在/etc/environment 中添加或更新一条配置记录

c++ - 编译时等效于 std::accumulate()

c++ - std::vector<std::basic_string<char>>::const_iterator' 没有名为 ‘c_str’ 的成员

c - 无法同步 FIFO 上的阻塞读取和写入

multithreading - 是否存在任何基于数组的、有界的、无等待的堆栈?

C# out参数问题: How does Out handle value types?

javascript - 在 javascript 中从堆栈中弹出原型(prototype)会导致未定义

php - Boost asio 接收 HTTP POST?

c++ - 更快的文件操作 C++

linux - 将 ROM 加载到 Emu OS