Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault: stack overflow [duplicate]

The following occurs in a linux 2.6.32-220.7.1.el6.x86_64 and g++ 4.4.6.

The following code:

#include <iostream>
#include <cstdlib>

int PROB_SIZE   = 10000000;
using namespace std;

int main(int argc, char *argv[])    {

    unsigned int numbers[PROB_SIZE];
    cout << "Generating " << PROB_SIZE << " random numbers... " << flush;

    return 0;
}

Produce the following SIGSEGV: (gdb) run Starting program: /home/cpd20202/sorting/error

Program received signal SIGSEGV, Segmentation fault.
0x000000000040093b in main (argc=1, argv=0x7fffffffe4f8) at error.cpp:13
13      cout << "Generating " << PROB_SIZE << " random numbers... " << flush;
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.47.el6_2.5.x86_64 libgcc-4.4.6-3.el6.x86_64 libstdc++-4.4.6-3.el6.x86_64
(gdb) where
#0  0x000000000040093b in main (argc=1, argv=0x7fffffffe4f8) at error.cpp:13

I'm really out of ideas.

like image 344
RSFalcon7 Avatar asked Dec 05 '22 16:12

RSFalcon7


1 Answers

It's because your array is larger than the size of the stack. Therefore, your program crashes when it tries to push something new during the function call.

The error you get is conceptually the same as a stack overflow, except it's caused by a local variable being incredibly large rather than by nesting too many function calls.

The stack is a small area of memory for use by functions for housekeeping and local variables. It's never really big, a few megabytes at most. This is why you will need a dynamic allocation to get rid of your problem. Most dynamic allocations will tap on the heap, which is often limited only by your physical memory.

You will need to allocate the array on the heap. For that, you have several options, the simplest of which probably being to use a std::vector<int>. They behave roughly the same as normal arrays and their storage is automatically managed, so this shouldn't be a problem.

#include <vector>
#include <iostream>

int PROB_SIZE   = 10000000;
using namespace std;

int main()
{
    vector<int> numbers(PROB_SIZE);
    cout << "Generating " << PROB_SIZE << " random numbers... " << flush;

    return 0;
}
like image 109
zneak Avatar answered Dec 09 '22 16:12

zneak