Segmentation Fault in C++

Last Updated : 19 Jun, 2026

A segmentation fault (Segfault) is a runtime error that occurs when a program attempts to access a memory location it is not allowed to access. It usually indicates an invalid memory operation such as dereferencing an invalid pointer, accessing memory after it has been freed, or writing outside the bounds of an array.

  • Occurs due to illegal or unauthorized memory access.
  • Usually results in immediate program termination.
  • Commonly caused by invalid pointers, buffer overflows, or stack overflows.

Causes of Segmentation Fault

A segmentation fault occurs when a program tries to access memory in an unauthorized or invalid way. It is commonly caused by issues such as dereferencing null or invalid pointers, accessing memory out of bounds, or improper memory management.

Modifying a String Literal

String literals are stored in read-only memory. Attempting to modify them results in undefined behavior and may cause a segmentation fault.

C++
#include <iostream>
using namespace std;

int main()
{
    char* str;

    // Stored in read only part of data segment //
    str = "GfG";

    // Problem:  trying to modify read only memory //
    *(str + 1) = 'n';
    return 0;
}

 Output

Segmentation Fault (SIGSEGV)
timeout: the monitored command dumped core
/bin/bash: line 1:    36 Segmentation fault      timeout 3s ./Solution < input.txt

Explanation: The statement *(str + 1) = 'n'; attempts to modify read-only memory.

Related Article: Storage for String in C

Accessing Freed Memory

After dynamically allocated memory is released using free() or delete, the pointer becomes a dangling pointer. Accessing it afterward results in undefined behavior and may cause a segmentation fault.

C++
#include <iostream>
using namespace std;

int main(void)
{
    // allocating memory to p
    int* p = (int*)malloc(sizeof(int));

    *p = 100;

    // deallocated the space allocated to p
    free(p);

    //  segmentation fault
    //  as now this statement is illegal
    *p = 110;

    return 0;
}

Output

Segmentation Fault

Explanation: The pointer refers to memory that has already been deallocated.

Accessing an Array Out of Bounds

Arrays in C++ do not perform automatic bounds checking. Accessing an invalid index may overwrite unrelated memory or trigger a segmentation fault.

C++
#include <iostream>
using namespace std;

int main()
{
    int arr[2];

    // Accessing out of bound
    arr[3] = 10;
    return 0;
}

Output

Segmentation Fault

Explanation: The program attempts to access memory outside the allocated array.

Incorrect Use of scanf()

The scanf() function expects the address of a variable as an input. Here in this program n takes a value of 2 and assumes its address as 1000. If we pass n to scanf(), input fetched from STDIN is placed in invalid memory 2 which should be 1000 instead. This causes memory corruption leading to a Segmentation fault.

C++
#include <cstdio>

int main() {
    int n;
    scanf("%d", n);   // Wrong: should be &n
}

Output

Segmentation Fault

Explanation: scanf() expects the address of a variable. Passing n instead of &n causes it to write to an invalid memory address.

Stack Overflow

A stack overflow occurs when the program consumes all available stack memory, usually because of infinite recursion or excessively large local variables.

C++
#include <iostream>
using namespace std;

int main()
{

    int array[2000000000];
    return 0;
}

Output

Segmentation Fault

Explanation: The large local array exceeds the available stack memory.

Buffer Overflow

Writing more data into a buffer than it can hold overwrites adjacent memory and may lead to a segmentation fault.

C++
#include <iostream>
using namespace std;

int main()
{

    char ref[20] = "This is a long string";
    char buf[10];
    sscanf(ref, "%s", buf);

    return 0;
}

Output

Segmentation Fault

Explanation: The destination buffer is smaller than the copied string, causing memory corruption.

Dereferencing an Uninitialized or NULL Pointer

Dereferencing a pointer that does not point to valid memory leads to undefined behavior and commonly results in a segmentation fault.

C++
#include <iostream>
using namespace std;

int main()
{
    int* ptr;
    int* nptr = NULL;
    cout << *ptr << " " << *nptr;
    return 0;
}

Output

(Segmentation Fault)

Explanation: Neither pointer refers to valid memory before dereferencing.

Identifying a Segmentation Fault

When a segmentation fault occurs, locating the exact source of the problem can be difficult. Debugging tools help identify the invalid memory access and the line of code responsible for it. Some commonly used tools include:

  • GDB for step-by-step debugging.
  • AddressSanitizer (ASan) for detecting memory errors during execution.
  • Valgrind for identifying invalid memory accesses, leaks, and dangling pointers.

Note: Some operating systems generate a core dump, which stores the program's memory state at the time of the crash and can be analyzed using a debugger.

Preventing Segmentation Faults

Following good memory management practices can help avoid segmentation faults.

  • Avoid modifying string literals or use the built in string container.
  • Being careful when using pointers as they are one of the most common causes. You can also use the smart pointers instead of raw pointers.
  • Considering the buffer and stack size before storing the data to avoid buffer or stack overflow.
  • Checking for bounds before accessing array elements or use STL containers such as vectors, sets, maps, etc.
  • Use scanf() and printf() carefully to avoid incorrect format specifiers or buffer overflow.
Comment