Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code giving runtime segmentation fault? [duplicate]

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

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
     int a[555555];
}
like image 513
manish Avatar asked Feb 08 '14 15:02

manish


People also ask

What causes segmentation fault errors?

In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).

How do I fix segmentation fault?

See if your compiler or library can be set to check bounds on [i] , at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers. Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems.


1 Answers

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
like image 104
haccks Avatar answered Sep 28 '22 20:09

haccks