Wednesday, October 14, 2009

SIGSEGV error in c++ programs

While solving a question TOANDFRO in spoj I was introduced to the SIGSEGV (segmentation fault) error. The very first thing, as I often do, I googled the error. The forums I visited and info I got simply did'nt tell me what exactly went wrong with my code. So, after a "deep-deep" analysis I m here to provide my readers with the solution to such an error.

There are various causes of segmentation faults, but fundamentally, you are accessing memory incorrectly. This could be caused by dereferencing a null pointer, or by trying to modify read only memory, or by using a pointer to somewhere that is not mapped into the memory space of your process.
A segfault basically means you did something bad with pointers. This is probably a segfault:

char *c = NULL;
...
*c; // dereferencing a NULL pointer

Or this:

char *c = "Hello";
...
c[10] = 'z'; // out of bounds, or in this case, writing into read-only memory

Or maybe this:

char *c = new char[10];
...
delete [] c;
...
c[2] = 'z'; // accessing freed memory

* * * * *

No comments:

Post a Comment