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.
- Segmentation Fault: It is the major reason for program to crash. These are may be the reasons for the such cause:
- Attempting to access memory location that doesn’t exist in our system.
- There may be an attempt to write on a read only memory location.
CPP
int main()
{
char *str;
str = "GfG";
*(str+1) = 'n' ;
return 0;
}
|
Segmentation fault (core dumped)
- There may be an attempt to access protected memory location such as kernel memory
- Stack Overflow: There may case of non terminating recursion with memory location.
CPP
#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)
- Buffer Overflow: It is an anomaly where a program, while writing data to a buffer, overruns the buffer’s boundary and overwrites adjacent memory locations.
- Consider below C++ program.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
char A[8] = "";
unsigned short B = 1979;
strcpy (A, "excessive");
return 0;
}
|
*** stack smashing detected ***: /home/gfg/a terminated
Aborted (core dumped)
- The program has two variables which are adjacent in memory: an 8-byte-long string buffer, A, and a two-byte big-endian integer, B.
char A[8] = “”; unsigned short B = 1979;
- Initially, A contains nothing but zero bytes, and B contains the number 1979. Now, the program attempts to store the null-terminated string “excessive” with ASCII encoding in the A buffer.
strcpy(A, “excessive”);
- This string is of 9 characters long and encodes to 10 bytes including the null terminator, but A can take only 8 bytes. By failing to check the length of the string, it also overwrites the value of B: B’s value has now been inadvertently replaced by a number formed from part of the character string. In this example “e” followed by a zero byte would become 25856. This overflow is called buffer overflow.
- Memory Leak: If we allocate some memory by some program and let it be as it is. After sometime there will be huge memory that is allocated but not used so this would lack of memory after sometime. And thus program start crashing.
CPP
#include<stdio.h>
int main()
{
for ( int i=0; i<10000000; i++)
{
int *ptr = ( int *) malloc ( sizeof ( int ));
}
}
|
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 10;
int y = 0;
cout << x/y;
return 0;
}
|
Floating point exception (core dumped)
Last Updated :
07 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...