Welcome to the next pikoTutorial!
The error we’re handling today is a C/C++ runtime error:
Segmentation fault (core dumped)
It can be represented also by the return code 139.
What does it mean?
A segmentation fault, often referred to as a ‘segfault,’ is a specific kind of error encountered in computing when a program tries to access a memory location that it is not allowed to access. Below you can find C++ examples of code causing a segmentation fault.
How to fix it?
Fixing segmentation fault depends on the reason why the segmentation fault occurred.
Dereferencing a null pointer
std::shared_ptr<int> a = nullptr;
std::cout << "a = " << *a; // dereferencing a nullptr
To avoid such situations, always check for validity of the pointers that you are going to use:
std::shared_ptr<int> a = nullptr;
if (a) {
std::cout << "a = " << *a;
}
else {
std::cerr << "a is a nullptr!";
}
Accessing memory beyond the array
std::array<int, 3> a {1, 2, 3};
std::cout << a[9999]; // trying to access 9999th element of 3 element array
To avoid terminating program in case of using invalid array index, use at
function instead of square braces. Using at
with invalid array index will still produce an error, but instead of segmentation fault it throws an exception which you can catch and handle.
std::array<int, 3> a {1, 2, 3};
try {
std::cout << a.at(9999);
}
catch (const std::out_of_range &e) {
std::cerr << "Error while accessing the array! " << e.what() << std::endl;
// handle invalid array access
}
The code above will produce the following output:
Error while accessing the array! array::at: __n (which is 9999) >= _Nm (which is 3)
Dereferencing a dangling pointer
int* a = new int(12);
delete a;
std::cout << *a;
To minimize the risk of dangling pointers, use smart pointers and static code analysis tool.