How to make a C++ program crash

In this article, we are going to learn about what are C++ crashes and what is the reason behind the crashes.

While writing codes we come across certain crashes in C++. Many a time, it takes plenty of time to identify and fix the crash. Here we are going to learn about the crashes and what causes these crashes. There are many types of crashes like a segmentation fault, memory leak, buffer overflow, etc. Some of them are explained below.

Segmentation fault in C++

#include<bits/stdc++.h>
using namespace std;

int main(){
int arr[3] = {5};

cout<<arr[1000];
}

It is a prime reason for a code to crash. The reasons for getting segmentation fault are -: 

  1. Trying to access memory that doesn’t exist.
    For example, if we are creating an array of size 10 and then we try to access array [1000] then it will show segmentation fault as this memory doesn’t exist but still, we are trying to access it. 
  2. . Trying to write on read-only memory  
    for example, we have created a character pointer say p = “hello”. Now, this is read-only memory we can’t write in it but still if we try to modify it like *(p + 1) = ‘hi’. Then it will show segmentation fault.
     

Buffer overflow in C++

#include<bits/stdc++.h>
using namespace std;

int main(){
char y[5] = "";
    unsigned short x = 1979;
    strcpy(y, "crash");
    return 0;
}

This error occurs when we try to insert extra data than allocated in a variable. For example, if we have created a string of say size 10 but we are trying to insert a string of size 15 then it will overflow the memory and will give buffer error. 

Memory leak in C++

#include<bits/stdc++.h>
using namespace std;

int main(){

     for (int j=0; j<100000009; j++)
    {
       // Allocating memory without freeing it
       int *p = (int *)malloc(sizeof(int));
    }
}

It occurs when we create a memory in a heap and then forget to delete it then the program will going to give this error. 

Also read: Fix a “use of undeclared identifier” compilation error in C++

Leave a Reply

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