C++ programs may crash unexpectedly for various reasons. Here are some typical causes of such crashes:
- Segmentation Fault
- A segmentation fault is a major cause of program crashes. It occurs when:
- Attempting to access a memory location that doesn’t exist.
- Trying to write to a read-only memory location.
- Accessing protected memory locations, such as kernel memory.
- Example:
- int main()
- {
- char *text;
- // Stored in the read-only part of the data segment
- text = "ABC";
- // Problem: trying to modify read-only memory
- *(text + 1) = 'n';
- return 0;
- }
- Stack Overflow
- Stack overflow happens due to non-terminating recursion, which exhausts the stack memory.
- Example:
#include <stdio.h>
void functionRecursive(int num)
{
if (num == 1)
return;
num = 6;
functionRecursive(num);
}
int main()
{
int number = 5;
functionRecursive(number);
}
- Buffer Overflow
- A buffer overflow occurs when a program writes data beyond the buffer’s boundary, overwriting adjacent memory locations.
- Example:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char data[8] = "";
unsigned short year = 1991;
strcpy(data, "excessive");
return 0;
}
- Memory Leak
- Memory leaks occur when a program allocates memory but fails to release it, gradually losing available memory.
- Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
for (int i = 0; i < 10000000; i++)
{
// Allocating memory without freeing it
int *memory = (int *)malloc(sizeof(int));
}
}
- Exceptions
- Exceptions, such as divide by zero, can also cause program crashes.
- Example:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int numerator = 10;
int denominator = 0;
cout << numerator / denominator;
return 0;
}
If you have any questions or doubts, feel free to comment below or contact me
directly. I’m here to help!
Better to use smart pointers to overcome memory leak issue
ReplyDeleteCorrect Prashant Sediwal, I will create blog how to avoid memory leak issue.
Delete