Learning about segmentation faults in C++

What happens when you try to access someone else’s locker in the gym? A space that is not allocated to you but you try to access it anyway. You cannot get in. In other words, it gives an error.

The same way if at any point in a program, memory space that is not allocated to a particular variable or code block is accessed a segmentation fault occurs, also called the core dump error.

This signifies that the program crashed because of two reasons:

  1. The program tried to access memory that does not belong to it.

  2. It tried to perform a write function in a read-only memory space.

The illustration below shows the kind of segments in memory different parts of the code can occupy.

Now that we know why a segmentation fault occurs and how the memory allocation is done, let’s look at a few examples of instances that lead to segmentation faults.

Examples of common segmentation faults

Segmentation faults can occur due to multiple reasons; overflowing the stack allocated during recursion, accessing array elements with out of bound indexes, referencing pointers that are freed, etc.

We will look at a few common examples of segmentation faults in C++.

1. An out of bounds access

The example below shows a segmentation fault that occurs when a value is modified or accessed at an index value greater than the array size.

Such a value of the index is inherently trying to access a memory space that does not belong to the array, hence the error.

#include <iostream>
using namespace std;
int main() {
int arr[5];
cout<<"Setting the value of index = 5, to 10. "<<endl;
arr[6] = 10;
}

2. Illegal memory access

The example below shows what happens when you try to allocate value to a pointer that has not been assigned any space in memory.

Since​ it does not have any memory allocated to it, it cannot set a value, giving a segmentation fault.

#include <iostream>
using namespace std;
int main() {
int* arr;
arr[5] = 10;
}

3. Writing to a read-only memory space

This happens when you try to modify a variable that exists in a read-only space. Since this is invalid access to memory space, it gives a segmentation fault. The pointer already has a value assigned to it, in its memory.

The assignment on line 7 is being done to an already assigned read-only memory block, hence there is an error.

#include <iostream>
using namespace std;
int main() {
int* number;
*number = 57;
*(number + 2) = 6;
}
Copyright ©2024 Educative, Inc. All rights reserved