DEV Community

Cover image for Segmentation Fault, how to get rid of it!
Saptarshi Basu
Saptarshi Basu

Posted on

Segmentation Fault, how to get rid of it!

It's very common for you to get a "Segmentation Fault" if you work with low level languages like C, C++ or Rust or even many more.
So the question is what's actually causing this error, is it that filthy pointer? maybe...

Segmentation Fault is a specific kinda error that arises when you try to access a unknown memory or that which doesn't belongs to you. There's quite a lot of ways you can get a segfault and to be honest its very hard to debug those memory stuffs. So I'll pointing out few of them that may help you to get rid of it (not sure).

First, a very common way to get a segfault is to dereference a null pointer.

int *ptr = NULL;
*ptr = 1;
Enter fullscreen mode Exit fullscreen mode

Another way you get a segfault is to change a read-only memory/value

char *str = "Foo"; // compiler marks the string as "read-only"
*str = 'b'; //changing read-only memory results in segfault
//or
const int foo = 1; //const keyword makes the variable read-only
foo = 2; //changing read-only var results in segfault
Enter fullscreen mode Exit fullscreen mode

And also another way of getting a segfault is pointing a pointer to a thing that doesn't exists anymore (I hope this is what they call it)

char *p = NULL;
{
   char c;
   p = &c;
}
//p - where is my reference to c ?
Enter fullscreen mode Exit fullscreen mode

Here, pointer p dangles as it points to c while its within the block but as soon as it get gets out of the block c has no existence and when you try again to dereference the pointer(now NULL) you probably will get a segfault.

Hope these examples might help you to cope up with your segfaults(maybe not). Why not share your views or solutions for handling segfaults in the comment section! :P

Top comments (1)

Collapse
 
deninpaulv profile image
Denin Paul

Thank you :D