DEV Community

Cover image for Bug of the week #5
pikoTutorial
pikoTutorial

Posted on • Originally published at pikotutorial.com

Bug of the week #5

Welcome to the next pikoTutorial !

The error we're handling today is a C/C++ runtime error:

Segmentation fault (core dumped)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

The code above will produce the following output:

Error while accessing the array! array::at: __n (which is 9999) >= _Nm (which is 3)
Enter fullscreen mode Exit fullscreen mode

Dereferencing a dangling pointer

int* a = new int(12);
delete a;
std::cout << *a;
Enter fullscreen mode Exit fullscreen mode

To minimize the risk of dangling pointers, use smart pointers and employ a static code analysis tool.

Top comments (0)