DEV Community

loading...
Cover image for Segmentation Fault in C

Segmentation Fault in C

courseprobe profile image Course Probe ・2 min read

What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?

Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory — accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C++.

There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer:

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

Another segfault happens when you try to write to a portion of memory that was marked as read-only:

char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault
Enter fullscreen mode Exit fullscreen mode

Dangling pointer points to a thing that does not exist anymore, like here:

char *p = NULL;
{
    char c;
    p = &c;
}
// Now p is dangling
Enter fullscreen mode Exit fullscreen mode

The pointer p dangles because it points to the character variable c that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'), you would probably get a segfault.

Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don’t find an error in your code, maybe a memtest could help you.

The solution in this case, change the RAM.

Hope this simple examples have been useful to better understand what is a segmentation fault.

Some interesting resources you might be interested in:

C/C++ Pointers & Applications

C Programming For Beginners — Master the C Language

Reference links:


Other Dev Posts:

Discussion (0)

pic
Editor guide