Core Dump (Segmentation fault) in C/C++

link 0

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 read and write operation in a read only location in memory or freed block of memory, it is known as core dump.
  • It is an error indicating memory corruption.

Common segmentation fault scenarios:

  • 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.

    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;
    }

    Abnormal termination of program.
    

     

  • 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 program to illustrate
    // Core Dump/Segmentation fault
    #include <stdio.h>
    #include<alloc.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;
    }

    Output:

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

    Output:

    Abnormal termination of program.

 

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar