Fundamentals 9 min read

13 Typical C Segmentation Fault Cases Every Programmer Should Know

This guide enumerates thirteen classic C segmentation fault patterns—including null pointer dereference, illegal memory access, stack overflow, buffer overrun, and misuse of dynamic memory—provides concise code examples for each, explains the underlying cause, and offers practical tips to prevent such crashes.

Liangxu Linux
Liangxu Linux
Liangxu Linux
13 Typical C Segmentation Fault Cases Every Programmer Should Know

Common Causes of Segmentation Faults in C

1. Dereferencing a Null Pointer

#include <stdio.h>
int main() {
    int *p = NULL;               // pointer does not refer to any object
    printf("%d
", *p);        // undefined behavior – dereferencing NULL
    return 0;
}

When a pointer is NULL it does not point to a valid memory region; dereferencing it triggers a segmentation fault.

2. Accessing Protected/System Memory

int *p = (int *)0x1;   // force pointer to an address that belongs to the kernel
*p = 100;               // attempt to write to a protected region

Operating on addresses that belong to the operating system or hardware is illegal and causes a fault.

3. Modifying a String Literal

char *str = "hello";   // stored in a read‑only segment
str[0] = 'H';           // attempt to write to read‑only memory

String literals reside in a read‑only area; any write operation leads to undefined behavior.

4. Stack Overflow via Infinite Recursion

void infinite_loop() {
    infinite_loop();   // recursive call without a base case
}
int main() {
    infinite_loop();   // quickly exhausts the call stack
    return 0;
}

Unbounded recursion consumes all stack space and results in a segmentation fault.

5. Array Out‑of‑Bounds Access

int arr[5];
arr[5] = 10;   // valid indices are 0‑4; index 5 is out of range

Accessing memory beyond the declared bounds of an array corrupts adjacent memory.

6. Using an Uninitialized (Wild) Pointer

int *p;          // pointer contains indeterminate value
*p = 42;         // dereferencing an invalid address

Before a pointer can be dereferenced it must be assigned a valid address (e.g., via malloc or by pointing to an existing object).

7. Use‑After‑Free

#include <stdlib.h>
int main() {
    int *p = malloc(sizeof(int));
    free(p);               // memory returned to the allocator
    *p = 10;               // undefined behavior – object no longer exists
    return 0;
}

Accessing memory after it has been released leads to heap corruption.

8. Buffer Overflow with strcpy

#include <string.h>
char buffer[5];
strcpy(buffer, "HelloWorld");   // copies more bytes than the buffer can hold

Standard library functions that do not perform size checks can easily overflow fixed‑size buffers.

9. Double Free

#include <stdlib.h>
int main() {
    int *p = malloc(sizeof(int));
    free(p);
    free(p);   // second free of the same block corrupts allocator state
    return 0;
}

Freeing the same pointer twice results in undefined behavior and often crashes.

10. Incorrect Forced Type Cast

int num = 42;
char *p = (char *)num;   // treat integer value as an address
*p = 'A';                // dereferencing an illegal address

Casting a non‑pointer value to a pointer and then dereferencing it is unsafe.

11. Mismatched Format String and Argument

#include <stdio.h>
char buf[64];
int data = 0;
sprintf(buf, "%s", data);   // expects a string, receives an int

Providing an argument of the wrong type to a format specifier yields undefined behavior.

12. Missing Null Terminator in a Character Array

#include <stdio.h>
int main() {
    char str[5] = {'H','e','l','l','o'}; // no '\0' terminator
    printf("%s
", str);                // prints until a random '\0' is found
    return 0;
}

Without a terminating '\0', functions that expect C‑strings read past the array bounds.

13. Assuming Same Size for Different Types

#include <stdlib.h>
int main() {
    char *p = (char *)malloc(10 * sizeof(int)); // allocate space for 10 ints
    int *q = (int *)p;                           // assume char and int have same size
    for (int i = 0; i < 10; ++i) {
        q[i] = i;                               // may write beyond allocated memory
    }
    free(p);
    return 0;
}

Incorrect assumptions about type sizes can cause out‑of‑bounds writes.

14. Wrong Format Specifier for an Integer

#include <stdio.h>
int main() {
    int num = 123;
    printf("%s
", num);   // should use %d for integers
    return 0;
}

Using an incompatible format specifier leads to unpredictable output.

15. Ignoring Return Value of fopen

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *file = fopen("nonexistent.txt", "r");
    if (!file) {
        // proper error handling should be here
        return 1;
    }
    // use file safely
    fclose(file);
    return 0;
}

Attempting to use a NULL FILE pointer after a failed fopen call can crash the program.

Prevention Checklist

Always initialize pointers and verify they are non‑NULL before dereferencing.

Perform bounds checking on arrays and buffers; prefer functions that accept size arguments (e.g., strncpy, snprintf).

Manage dynamic memory carefully: check the result of malloc/calloc, free each allocation exactly once, and set pointers to NULL after freeing.

Do not modify string literals; copy them into a mutable buffer if modification is required.

Validate return values of library functions (e.g., fopen, scanf, malloc) and handle errors appropriately.

Avoid deep or infinite recursion; consider iterative solutions or increase stack size only when necessary.

Use the correct format specifiers that match the argument types.

When casting, ensure the source value truly represents a valid address and that the target type size is appropriate.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Memory Managementc++pointerssegmentation fault
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.