Open In App

Reasons for a C++ program crash

We sometimes come across abnormal crash of C++ programs. Below are some possible reasons which may cause C++ to crash abnormally.




// CPP program to demonstrate
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;
}

Segmentation fault (core dumped)




// C program to demonstrate stack overflow
// by creating a non-terminating recursive
// function.
#include<stdio.h>
 
void fun(int x)
{
    if (x == 1)
       return;
    x = 6;
    fun(x);
}
 
int main()
{
   int x = 5;
   fun(x);
}

Segmentation fault (core dumped)




// C++ code to demonstrate buffer
// overflow.
#include <bits/stdc++.h>
using namespace std;
 
// driver code
int main()
{
    char A[8] = "";
    unsigned short B = 1979;
    strcpy(A, "excessive");
    return 0;
}

*** stack smashing detected ***: /home/gfg/a terminated
Aborted (core dumped)

char A[8] = “”; unsigned short B = 1979;

strcpy(A, “excessive”);




// C program to demonstrate heap overflow
// by continuously allocating memory
#include<stdio.h>
  
int main()
{
    for (int i=0; i<10000000; i++)
    {
       // Allocating memory without freeing it
       int *ptr = (int *)malloc(sizeof(int));
    }
}




// C++ code to demonstrate divide by 0.
#include <bits/stdc++.h>
using namespace std;
 
// driver code
int main()
{
    int x = 10;
    int y = 0;
    cout << x/y;
    return 0;
}

Floating point exception (core dumped)

Article Tags :