Skip to content
Related Articles
Open in App
Not now

Related Articles

Segmentation Fault in C/C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 05 Mar, 2023
Improve Article
Save Article
Like Article

Segmentation faults in C/C++ occur when a program attempts to access a memory location it does not have permission to access. Generally, this occurs when memory access is violated and is a type of general protection fault.

The core dump refers to the recording of the state of the program, i.e. its resources in memory and processor. Trying to access non-existent memory or memory which is being used by other processes also causes the Segmentation Fault (core dumped). 

A program has access to specific regions of memory while it is running. First, the stack is used to hold the local variables for each function. Moreover, it might have memory allocated at runtime and saved on the heap (new in C++ and you may also hear it called the “free store“). The only memory that the program is permitted to access is its own (the memory previously mentioned). A segmentation fault will result from any access outside of that region. 

Segfaults are the abbreviation for segmentation faults. In simple terms, Segfaults are caused by a program trying to read or write from/on an invalid memory location.

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you” 

  • When a piece of code tries to do a read-and-write operation in a read-only location in memory or freed block of memory, it is known as a core dump.
  • It is an error indicating memory corruption.

Common Segmentation Fault Scenarios

In a Segmentation fault, a program tries to access memory that is not authorized to access, or that does not exist. Some common scenarios that can cause segmentation faults are:

  1. Modifying a string literal
  2. Accessing an address that is freed
  3. Accessing out-of-array index bounds
  4. Improper use of scanf()
  5. Stack Overflow 
  6. Dereferencing uninitialized pointer 

Modifying a string literal

The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read-only memory.

Example: 

C




// C program to demonstrate segmentation fault/core dump
// by modifying a string literal
#include <stdio.h>
  
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;
}


C++




// C++ program to demonstrate segmentation fault/core dump
// by modifying a string literal
#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:

timeout: the monitored command dumped core
/bin/bash: line 1:    32 Segmentation fault      timeout 15s ./83b16132-8565-4cb1-aedb-4eb593442235 < 83b16132-8565-4cb1-aedb-4eb593442235.in

Refer, to Storage for Strings in C for more details 

Accessing an address that is freed 

Here in the below code, the pointer p is dereferenced after freeing the memory block, which is not allowed by the compiler. So it produces the error segment fault or abnormal program termination at runtime. 

Example:

C




// C program to demonstrate segmentation fault/core dump
// by Accessing an address that is freed
#include <alloc.h>
#include <stdio.h>
int main(void)
{
    // allocating memory to p
    int* p = malloc(8);
    *p = 100;
  
    // deallocated the space allocated to p
    free(p);
  
    // core dump/segmentation fault
    //  as now this statement is illegal
    *p = 110;
  
    return 0;
}


C++




// C++ program to demonstrate segmentation fault/core dump
// by Accessing an address that is freed
#include <iostream>
using namespace std;
  
int main(void)
{
    // allocating memory to p
    int* p = (int*)malloc(8 * sizeof(int));
  
    *p = 100;
  
    // deallocated the space allocated to p
    free(p);
  
    // core dump/segmentation fault
    //  as now this statement is illegal
    *p = 110;
  
    return 0;
}


Output: 

Abnormal termination of program.

Accessing out-of-array index bounds

 In C++, accessing out-of-array index bounds may cause a segmentation fault or other undefined behavior. Boundary-checking array accesses, such as with the std::vector::at() method or with an if() statement, can prevent accessing out-of-array index bounds.

Example:

C




// C program to demonstrate segmentation
// fault when array out of bound is accessed.
#include <stdio.h>
  
int main(void)
{
    int arr[2];
  
    // Accessing out of bound
    arr[3] = 10;
  
    return (0);
}


C++




// C++ program to demonstrate segmentation
// fault when array out of bound is accessed.
#include <iostream>
using namespace std;
  
int main()
{
    int arr[2];
  
    // Accessing out of bound
    arr[3] = 10;
    return 0;
}


Output: 

Abnormal termination of program.

Improper use of scanf()

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. It’s a memory corruption leading to a Segmentation fault.

Example:

C




// C program to demonstrate segmentation
// fault when value is passed to scanf
#include <stdio.h>
  
int main()
{
    int n = 2;
    scanf(" ", n);
    return 0;
}


C++




// C++ program to demonstrate segmentation
// fault when value is passed to scanf
#include <iostream>
using namespace std;
  
int main()
{
    int n = 2;
    cin >> " " >> n;
    return 0;
}


Output:

Abnormal termination of program.

Stack Overflow 

It’s not a pointer-related problem even code may not have a single pointer. It’s because the recursive function gets called repeatedly which eats up all the stack memory resulting in a stack overflow. Running out of memory on the stack is also a type of memory corruption. It can be resolved by having a base condition to return from the recursive function.

Dereferencing an uninitialized pointer 

It is a common programming error to dereference an uninitialized pointer, which can result in undefined behavior. When a pointer is used in a context that treats it as a valid pointer and accesses its underlying value, even though it has not been initialized to point to a valid memory location, this error occurs. Data corruption, program errors, or segmentation faults can result from this. Depending on their environment and state when dereferencing, uninitialized pointers may yield different results. All pointers must be properly initialized before being used in order to avoid this error. 

Example:

C




// C program to demonstrate segmentation
// fault when uninitialized pointer is accessed.
#include <stdio.h>
  
int main()
{
    int* p;
    printf("%d", *p);
    return 0;
}


C++




// C++ program to demonstrate segmentation
// fault when uninitialized pointer is accessed.
#include <iostream>
using namespace std;
  
int main()
{
    int* p;
    cout << *p;
    return 0;
}


This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!