5

Why is this code giving segmentation fault? I am using code::blocks.

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
     int a[555555];
}
Deanie
  • 2,316
  • 2
  • 19
  • 35
manish
  • 301
  • 1
  • 3
  • 10

5 Answers5

10

This is what called stack overflow.
Generally stack size are small and you can't allocate memory in such a large amount on stack.
For this purpose programmers allocate it on heap (using dynamic allocation). In C, you can use malloc family function

int *a = malloc(sizeof(int)*55555); // Use free(a) to deallocate

In C++ you can use new operator

int *b = new int[555555];   // Use delete [] to deallocate
Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
4

Because you are trying to allocate a bit over 2MB (Previously I failed at math and thought it was 2GB) of memory on stack, which then blows the stack.

Note: for windows the default stack size for a particular thread is 1MB and on Gnu/linux you can find out stack size value using ulimit -s command.

Marco
  • 6,692
  • 2
  • 27
  • 38
Xarn
  • 3,460
  • 1
  • 21
  • 43
3

You've come to the right place to ask the question. ;)

The array is large and lives on the stack. The code crashes because it runs out of the limited stack space.

If you allocate a on the heap, the problem will likely disappear.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

As other already had told you you are trying to allocate a large amount of memory in the stack which space is usually very limited.

See for instance:

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
     int a[555555];
     int* b = new int[555555];

     delete [] b;
}

In that snipped, you have two arrays of integers, one allocated in the heap and the other allocated on the stack.

Here you can find some explanations about which are the differences between the heap and the stack:

What and where are the stack and heap? http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

Community
  • 1
  • 1
Pedrom
  • 3,823
  • 23
  • 26
0

I've got some considerations on your code.
First, modern compilers will recognize that a is unused and then it'll be thrown away.
But if you put a certain value into a certain position, a will be allocated, even though it's bigger than the stack size. The kernel will not allow you do that: that's why you get a SIGSEGV.
Finally, you should rely on either std::array or std::vector rather than pure C arrays.

edmz
  • 8,220
  • 2
  • 26
  • 45