Segmentation Fault in C: What It Means and How to Fix It
"Segmentation fault (core dumped)" is the message every C programmer meets sooner or later. It tells you very little, which is why it feels so frustrating. This guide explains what it means and walks through the causes you are most likely to hit.
What actually happens
Your operating system gives each program its own region of memory. If your program reads or writes memory outside that region, or uses memory in a way that is not allowed, the hardware raises a fault and the operating system stops the program immediately. C does not check these accesses for you, so the compiler will happily build code that crashes at runtime.
Cause 1: dereferencing a NULL pointer
int *p = NULL;
*p = 10; /* crash */
Fix: check a pointer before using it, and always check the result of malloc.
int *p = malloc(sizeof(int));
if (p == NULL)
{
return (1);
}
*p = 10;
Cause 2: an uninitialized pointer
int *p;
*p = 10; /* p holds a random address */
A pointer that was never assigned holds garbage. Point it at real memory first, either a variable (int x; int *p = &x;) or a block from malloc.
Cause 3: going far past the end of an array
int a[3] = {1, 2, 3};
a[100000] = 5;
Small overruns often corrupt neighboring data quietly. Large ones leave your program's memory entirely and crash. Our guide to off-by-one errors covers the small ones.
Cause 4: using memory after it was freed
Reading or writing through a pointer after free is undefined behavior and can crash. See dangling pointers in C.
Cause 5: infinite recursion
int count(int n)
{
return (count(n + 1));
}
Each call uses a little stack memory. With no base case the stack runs out, which also ends in a segmentation fault. Every recursive function needs a condition that stops it.
Cause 6: changing a string literal
char *s = "hello";
s[0] = 'H'; /* undefined behavior, usually a crash */
String literals are stored in read-only memory. If you need to change the text, make a copy:
char s[] = "hello";
s[0] = 'H'; /* fine */
How to find the exact line
Compile with debug symbols and AddressSanitizer, then run the program again:
gcc -g -fsanitize=address -o app app.c
./app
AddressSanitizer prints the kind of error and the exact line where it happened. You can also use the debugger:
gdb ./app
(gdb) run
(gdb) bt
The bt command shows the chain of function calls that led to the crash.
Prevention checklist
- Initialize every pointer to a valid address or to NULL
- Check the return value of
malloc - Compare array indexes with the array size
- Set a pointer to NULL after freeing it
- Give every recursive function a base case
- Compile with
-Wall -Wextraand read the warnings
If pointers still feel confusing, start with what a pointer is and then come back to this list.