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:
- Division by zero.
- Segmentation faults.
- Large memory allocation/Large Static Memory Allocation.
- Type Specifier Error.
- Invalid memory access during runtime.
Let’s start discussing each of these runtime errors in detail.