Skip to content

Segmentation Faults

What is a segmentation fault?

A segmentation fault (also known as a segfault) is caused when code attempts to access memory that it doesn't have permission to access. Every program is given a piece of memory (RAM) to work with and it is only allowed to access memory in that chunk.

If your process crashed and you see an error reporting that a segmentation fault has occurred, the problem is most likely in your code or a 3rd party code that you are using. One exception is when the segfault occurs because your program ran out of stack space. See the section Running out of stack space below on how to correct this problem.

Common segfault scenarios

In practice, segfaults are often due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or accidentally using a variable's value as an address. Below, you will find several common scenarios that result in segfaults.

Attempting to read or write past the end of an array

An array is a contiguous region of memory, where each successive element is located at the next address in memory. Most arrays don't have a sense of how large they are, or what the last element is, making it easy to blow past the end of the array without knowing it. If you read or write past the end of the array, you may wind up going into memory that is uninitialized or belongs to something else.

Attempting to operate on a memory location in a way that is not allowed

An example of this would be attempting to write to a read-only location.

Accessing a NULL or uninitialized pointer

If you have a pointer that is NULL (ptr=0) or that is completely uninitialized (it isn't set to anything at all yet), attempting to access memory or modify memory using that pointer will have undefined behavior.

Running out of stack space

Segfaults can also occur when your program runs out of stack space. This may not be a bug in your program, but may be due to your shell setting the stack size limit to a value that is too small. The usual remedy is to increase the stack size and re-run your program. For example, to set the stack size to unlimited, add this line to your job submission script:

ulimit -s unlimited