7 Deadly Causes of Segmentation Fault in C (With Code Fixes)
Segmentation faults—those dreaded "Segmentation fault (core dumped)" messages—can crash your C programs without mercy. If you're debugging a tricky bug, understanding the segment fault in c is crucial. These errors happen when your code tries to access memory it's not allowed to, like invalid pointers or array bounds violations. In this post, we'll break down the segment fault in c with example and dive into seven common culprits, complete with buggy code and fixes. Whether you're a student tackling segment fault in c geeksforgeeks-style problems or a pro hunting production bugs, these tips will save you hours.
1. Dereferencing NULL Pointers
The most infamous cause: forgetting to check if a pointer is NULL before using it. In C, malloc() or user input can return NULL, and dereferencing it accesses invalid memory.
Buggy Code:
#include #include int main() { int *ptr = malloc(sizeof(int)); free(ptr); // Now ptr is a dangling pointer *ptr = 42; // Boom! Segfault. return 0; } Fix: Always initialize pointers to NULL and check before dereferencing. Use defensive coding.
Fixed Code:
#include #include int main() { int *ptr = NULL; ptr = malloc(sizeof(int)); if (ptr != NULL) { *ptr = 42; free(ptr); } return 0; } This prevents crashes from uninitialized or freed pointers. Pro tip: Tools like Valgrind catch these early.
2. Array Out-of-Bounds Access
C arrays lack bounds checking, so straying beyond limits reads or writes invalid memory.
Buggy Code:
#include int main() { int arr[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 5; i++) { // i=5 is out of bounds! printf("%dn", arr[i]); } return 0; } Fix: Use loops that respect bounds or functions like memset() carefully.
Fixed Code:
#include int main() { int arr[5] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { // Strict < 5 printf("%dn", arr[i]); } return 0; } For dynamic arrays, consider safer alternatives like vectors in C++ or bounds-checked libraries.
3. Stack Overflow from Recursion
Deep recursion without a base case overflows the stack, triggering a segfault.
Buggy Code:
#include void recurse(int n) { if (n <= 0) return; // Weak base case recurse(n - 1); } int main() { recurse(10000); // Stack overflow! return 0; } Fix: Add proper base cases and tail recursion where possible.
Fixed Code:
#include void recurse(int n) { if (n <= 0) return; // Solid base printf("%dn", n); if (n > 1) recurse(n - 1); // Iterative feel } int main() { recurse(10); // Safe depth return 0; } Monitor stack size with ulimit -s on Linux.
4. Uninitialized Pointers
Pointers default to garbage values if not set, leading to random memory access.
Buggy Code:
#include int main() { int *ptr; // Uninitialized! *ptr = 10; // Points to who-knows-where. return 0; } Fix: Zero them out explicitly.
Fixed Code:
#include int main() { int *ptr = NULL; // Safe default if (ptr) *ptr = 10; // Won't execute return 0; } Compile with -Wall -Wextra to spot these.
5. Dangling Pointers After Free
Freeing memory leaves pointers dangling, and reusing them segfaults.
Buggy Code:
#include #include int main() { int *ptr = malloc(sizeof(int)); free(ptr); *ptr = 5; // Dangling! return 0; } Fix: Set to NULL post-free.
Fixed Code:
#include #include int main() { int *ptr = malloc(sizeof(int)); free(ptr); ptr = NULL; // No more dangling return 0; } This is key for how to solve segmentation fault in C.
6. Invalid Memory Access in Strings
Null-terminator mishaps or buffer overflows in string ops like strcpy().
Buggy Code:
#include #include int main() { char buf[5]; strcpy(buf, "Hello"); // Overflow! No null check. printf("%sn", buf); return 0; } Fix: Use strncpy() and ensure space.
Fixed Code:
#include #include int main() { char buf[10]; strncpy(buf, "Hello", sizeof(buf) - 1); buf[sizeof(buf) - 1] = ' '; printf("%sn", buf); return 0; } See a full segmentation fault in C example in action.
7. Function Pointer Misuse
Calling uninitialized or wrong-type function pointers.
Buggy Code:
#include int add(int a, int b) { return a + b; } int main() { int (*func)(); // Wrong signature! func = add; printf("%dn", func(2, 3)); // Mismatch crash. return 0; } Fix: Match signatures precisely.
Fixed Code:
#include int add(int a, int b) { return a + b; } int main() { int (*func)(int, int) = add; // Correct type printf("%dn", func(2, 3)); return 0; } Debugging and Prevention Tips
To tackle what causes a segmentation fault in C, use GDB: gdb ./a.out, then run and bt on crash. For how to fix segmentation fault, enable AddressSanitizer (gcc -fsanitize=address). These seven causes cover 90% of cases—master them, and your C code will run smoothly.