Why do I get a segmentation fault in C?
What causes a segmentation fault
A segmentation fault (segfault) is a hardware signal (SIGSEGV) sent to your program when it accesses invalid memory. In C, this often happens due to pointer errors: using a pointer that is NULL, uninitialized, or already freed.
Other causes include writing past the bounds of an array, using a large local variable that overflows the stack, or calling a function through a bad function pointer.
How to debug and fix it
Use a debugger like GDB to get a backtrace and identify the line of code causing the fault. Compile with -g to include debug symbols. Tools like Valgrind can detect memory errors like invalid reads/writes and leaks.
Check all pointer dereferences: ensure pointers are initialized, point to valid memory, and are not used after free. For arrays, verify indices are within bounds. For strings, ensure null termination.
- Initialize pointers to NULL and check before dereferencing.
- Use sizeof correctly when allocating memory: malloc(n * sizeof(int)).
- Avoid returning pointers to local variables.
- Use strncpy instead of strcpy to avoid buffer overflows.
- Enable compiler warnings (-Wall -Wextra) to catch potential issues.
Common scenarios
A classic example: int *p; *p = 5; — p is uninitialized, so writing to it causes a segfault. Another: char *str = "hello"; str[0] = 'H'; — string literals are read-only, so writing to them segfaults.
Stack overflow can also cause a segfault, often due to infinite recursion or very large local arrays. Increase stack size or use heap allocation if needed.
Common mistakes
- Assuming a segfault always means a null pointer — it can also be due to out-of-bounds access or use-after-free.
- Ignoring compiler warnings that point to potential pointer issues.
- Not checking the return value of malloc, which can return NULL if allocation fails.
