1

I get the segmentation fault when i want to allocate this array and output first element. I know that this element not initialized, but why segmentation fault? Code:

#include <iostream>

using namespace std;

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

Tested on OSX with(1GB free memory) and on Ubuntu 12.04(with about 15gb free memory).

PS: I was sure that in linux we can allocate big arrays on stack.

Compilers tried:

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

ERRORS:

OSX:

Segmentation fault: 11

UBUNTU: Segmentation fault

Sukhanov Niсkolay
  • 1,298
  • 1
  • 12
  • 26

1 Answers1

7

Default installation of Ubuntu has this limits for user-space processes:

$ 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

So, the stack size is limited to 8192 KB. You program needs more, so OS just kill it.

Try to use dynamic allocation for your adj array or (not recommended) increase the limit via ulimit -s 32768 command.

qehgt
  • 2,972
  • 1
  • 22
  • 36
  • 1
    Thanks a lot, your answer is very helpful, i know about dynamic allocation, but stack allocation is often uses in competetive programming and olympiads. And i've done it before without problems. So i want to ask, was it always? 8mb default stack size? – Sukhanov Niсkolay Jun 02 '14 at 16:45
  • 1
    @SukhanovNiсkolay, it depends on a specific Linux distributive. For example, RedHat/Centos use 10240 by default. – qehgt Jun 02 '14 at 16:57
  • 1
    @SukhanovNiсkolay are you sure you've done it with `long long` (which is 8 bytes)? If you change it to `int` (which most often is 4 bytes) it will work quite often. – vsoftco Jun 02 '14 at 16:58
  • Yeah, i'm sure about size. But i'm not sure about distributive. So thanks to all. – Sukhanov Niсkolay Jun 03 '14 at 16:23