Segmentation Faults

In the below code, the line *(str + 1) = ‘n’ tries to write to read-only memory. Below is the C++ program to demonstrate segmentation fault:

C++




// C++ program to demonstrate 
// segmentation fault
#include <iostream>
using namespace std;
  
// Driver code
int main()
{
  char *str;
    
  // Stored in read only part 
  // of data segment 
  str = "w3wiki";    
    
  // Trying to modify read only 
  // memory
  *(str + 1) = 'n';
  return 0;
}


Output: 

 

C++ Program to Show Runtime Exceptions

A runtime error occurs while the program is running. Because this is not a compilation error, the compilation will be completed successfully. Here, we will learn how to handle runtime exceptions in C++. 

There are 5 types of runtime exceptions discussed here:

  1. Division by zero. 
  2. Segmentation faults. 
  3. Large memory allocation/Large Static Memory Allocation.
  4. Type Specifier Error.
  5. Invalid memory access during runtime.

Let’s start discussing each of these runtime errors in detail.

Similar Reads

1. Division By Zero

When we divide an integer value by zero then we get this type of error called division by zero error. It is also called floating-point exceptions (SIGFPE). Below is the C++ program to demonstrate division by zero exception:...

2. Segmentation Faults

...

3. Large memory Allocation/Large Static Memory Allocation

In the below code, the line *(str + 1) = ‘n’ tries to write to read-only memory. Below is the C++ program to demonstrate segmentation fault:...

4. Type Specifier Error

...

5. Invalid Memory Access During Runtime

In general, any compiler or any language will accept up to 10^8. However, to be on the safe side we generally used up to 10^7. In the below code, the size of the array is more than 10^8 so here we got an error due to large memory allocation. It is also called an abort signal (SIGABRT)....