C Programming Systems Programming

How to Fix 'Segmentation Fault (core dumped)' in C / C++

Error Message
Segmentation fault (core dumped)
Quick Fix
gcc -g program.c -o program && gdb ./program (gdb) run (gdb) backtrace

Why Does This Happen?

A segfault (SIGSEGV) happens when your program accesses a memory address it does not own — typically a NULL pointer, an out-of-bounds array index, or writing to read-only memory.

Step-by-Step Solution

1
Cause 1: NULL or Uninitialized Pointer
Always check malloc() return value and initialise pointers:
Terminal / Code
// BUG:
int *ptr = NULL;
*ptr = 42;  // CRASH

// FIX:
int *ptr = malloc(sizeof(int));
if (!ptr) { perror("malloc"); return 1; }
*ptr = 42;
free(ptr);
malloc() returns NULL when the system is out of memory.
2
Cause 2: Writing to a String Literal
String literals live in read-only memory:
Terminal / Code
// BUG:
char *s = "Hello";
s[0] = 'h';  // CRASH

// FIX:
char s[] = "Hello";  // stack-allocated, modifiable
s[0] = 'h';  // OK
Use char s[] for strings you need to modify.
3
Cause 3: Array Out of Bounds
C does not do bounds checking — writing past an array corrupts the stack:
Terminal / Code
int arr[5];
arr[100] = 99;  // CRASH — out of bounds

// FIX: respect the declared size
for (int i = 0; i < 5; i++) arr[i] = i;
C trusts the programmer completely. There is no runtime array guard.
4
Debug with GDB in 60 seconds
Compile with -g for debug symbols and run gdb to get the exact crashing line:
Terminal / Code
gcc -g main.c -o main
gdb ./main
(gdb) run
(gdb) backtrace
backtrace prints the full function call chain at the moment of crash.

Common Mistakes to Avoid

Forgetting & in scanf: scanf("%d", num) instead of scanf("%d", &num) — num is used as a raw address!
Double-freeing a pointer (free() called twice on the same block).

Frequently Asked Questions

What tool detects segfaults automatically?
Valgrind: valgrind --leak-check=full ./program. Or compile with AddressSanitizer: gcc -fsanitize=address -g program.c -o program.

Learn to Write Code That Doesn't Break

DoxaTech Hub's 10-month programme teaches you Git internals, Linux systems, C, Python, SQL, Docker, and React from first principles — so you spend less time fixing errors and more time shipping.

Start Learning →