I need to know the root cause of the segmentation fault (SIGSEGV), and how to handle it.
SigSegV means a signal for memory access violation, trying to read or write from/to a memory area that your process does not have access to. These are not C or C++ exceptions and you can’t catch signals. It’s possible indeed to write a signal handler that ignores the problem and allows continued execution of your unstable program in undefined state, but it should be obvious that this is a very bad idea.
Most of the time this is because of a bug in the program. The memory address given can help debug what’s the problem (if it’s close to zero then it’s likely a null pointer dereference, if the address is something like 0xadcedfe then it’s intentional safeguard or a debug check, etc.)
One way of “catching” the signal is to run your stuff in a separate child process that can then abruptly terminate without taking your main process down with it. Finding the root cause and fixing it is obviously preferred over workarounds like this.
using an invalid/null pointer? Overrunning the bounds of an array? Kindof hard to be specific without any sample code.
Essentially, you are attempting to access memory that doesn't belong to your program, so the OS kills it.
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 readonly memory, or by using a pointer to somewhere that is not mapped into the memory space of your process (that probably means you are trying to use a number as a pointer, or you incremented a pointer too far). On some machines, it is possible for a misaligned access via a pointer to cause the problem too - if you have an odd address and try to read an even number of bytes from it, for example (that can generate SIGBUS, instead).
The initial source cause can also be an out of memory.
Wikipedia has the answer, along with a number of other sources.
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
Same basic principle in each case - you're doing something with memory that isn't yours.
segmentation fault arrives when you access memory which is not declared by the program. You can do this through pointers i.e through memory addresses. Or this may also be due to stackoverflow for eg:
void rec_func() {int q = 5; rec_func();}
int main() {rec_func();}
This call will keep on consuming stack memory until it's completely filled and thus finally stackoverflow happens. Note: it might not be visible in some competitive questions as it leads to timeouterror first but for those in which timeout doesn't happens its a hard time figuring out sigsemv.