Memory-related errors in c/c++
Memory-related errors are among the most dangerous bugs in C/C++ because they can cause crashes, data corruption, security vulnerabilities, and unpredictable behavior. Understanding these errors is essential for every software developer, especially in embedded systems, device drivers, and performance-critical applications.
Memory-related errors are among the most dangerous bugs in C/C++ because they can cause crashes, data corruption, security vulnerabilities, and unpredictable behavior. Understanding these errors is essential for every software developer, especially in embedded systems, device drivers, and performance-critical applications.
1. Null Pointer Dereference
What is it?
A program attempts to access memory through a pointer that contains NULL or nullptr.
A program attempts to access memory through a pointer that contains NULL or nullptr.
Example
int *ptr = nullptr;*ptr = 10; // Crash
Why does it occur?
- Pointer not initialized
- Function returns nullptr and caller does not check
- Object creation fails
- Pointer not initialized
- Function returns nullptr and caller does not check
- Object creation fails
Symptoms
- Segmentation Fault
- Access Violation
- Segmentation Fault
- Access Violation
Solution
Always validate pointers before use.
if(ptr != nullptr){ *ptr = 10;}Use smart pointers when possible.
Always validate pointers before use.
Use smart pointers when possible.
2. Wild Pointer (Uninitialized Pointer)
What is it?
A pointer contains garbage data because it was never initialized.
A pointer contains garbage data because it was never initialized.
Example
int *ptr;*ptr = 10; // Undefined behavior
Why does it occur?
Developer forgets initialization.
Developer forgets initialization.
Symptoms
- Random crashes
- Memory corruption
- Intermittent bugs
- Random crashes
- Memory corruption
- Intermittent bugs
Solution
Initialize pointers immediately.
int *ptr = nullptr;or
int value;int *ptr = &value;
Initialize pointers immediately.
or
3. Dangling Pointer
What is it?
Pointer points to memory that no longer exists.
Pointer points to memory that no longer exists.
Example
int* GetValue(){ int x = 5; return &x;}After function exits, x is destroyed.
After function exits, x is destroyed.
Why does it occur?
- Returning local variable address
- Object destroyed
- Memory freed
- Returning local variable address
- Object destroyed
- Memory freed
Symptoms
- Random crashes
- Incorrect values
- Random crashes
- Incorrect values
Solution
Never return addresses of local variables.
int GetValue(){ int x = 5; return x;}
Never return addresses of local variables.
4. Use After Free
What is it?
Memory is accessed after it has been released.
Memory is accessed after it has been released.
Example
int *ptr = new int(20);delete ptr;cout << *ptr; // Error
Why does it occur?
- Object deleted but pointer remains
- Multiple pointers sharing memory
- Object deleted but pointer remains
- Multiple pointers sharing memory
Symptoms
- Crashes
- Corrupt data
- Security vulnerabilities
- Crashes
- Corrupt data
- Security vulnerabilities
Solution
Set pointer to nullptr after deleting.
delete ptr;ptr = nullptr;Better:
std::unique_ptr<int> ptr = std::make_unique<int>(20);
Set pointer to nullptr after deleting.
Better:
5. Double Free
What is it?
Same memory is released twice.
Same memory is released twice.
Example
int *ptr = new int;delete ptr;delete ptr; // Error
Why does it occur?
- Poor ownership management
- Multiple pointers owning same memory
- Poor ownership management
- Multiple pointers owning same memory
Symptoms
- Heap corruption
- Program crashes
- Heap corruption
- Program crashes
Solution
delete ptr;ptr = nullptr;Use RAII and smart pointers.
std::unique_ptr<int>
Use RAII and smart pointers.
6. Buffer Overflow
What is it?
Writing beyond allocated memory boundaries.
Writing beyond allocated memory boundaries.
Example
char name[10];strcpy(name,"HelloWorld123");
Why does it occur?
- Array size not checked
- User input larger than buffer
- Array size not checked
- User input larger than buffer
Symptoms
- Stack corruption
- Random crashes
- Security exploits
- Stack corruption
- Random crashes
- Security exploits
Solution
Use size-limited functions.
strncpy(name, input, sizeof(name)-1);Or use:
std::string
Use size-limited functions.
Or use:
7. Buffer Underflow
What is it?
Accessing memory before beginning of buffer.
Accessing memory before beginning of buffer.
Example
int arr[10];arr[-1] = 5;
Why does it occur?
Incorrect indexing.
Incorrect indexing.
Symptoms
- Data corruption
- Crashes
- Data corruption
- Crashes
Solution
Validate indexes.
if(index >= 0 && index < size){ arr[index] = value;}
Validate indexes.
8. Stack Overflow
What is it?
Program consumes more stack memory than available.
Program consumes more stack memory than available.
Example
Infinite recursion:
void Func(){ Func();}
Infinite recursion:
Why does it occur?
- Infinite recursion
- Huge local arrays
- Infinite recursion
- Huge local arrays
Symptoms
- Stack Smashing
- Segmentation Fault
- Stack Smashing
- Segmentation Fault
Solution
Limit recursion depth.
Avoid large stack variables.
std::vector<int> data(1000000);Use heap memory for large data.
Limit recursion depth.
Avoid large stack variables.
Use heap memory for large data.
9. Memory Leak
What is it?
Allocated memory is never released.
Allocated memory is never released.
Example
void Func(){ int *ptr = new int[100];}Memory lost after function exits.
Memory lost after function exits.
Why does it occur?
Forgot to call delete.
Forgot to call delete.
Symptoms
- Increasing RAM usage
- Slow system
- Out-of-memory errors
- Increasing RAM usage
- Slow system
- Out-of-memory errors
Solution
delete[] ptr;Best approach:
std::vector<int>std::unique_ptr
Best approach:
10. Heap Corruption
What is it?
Program damages heap management structures.
Program damages heap management structures.
Example
char *ptr = new char[10];for(int i=0;i<50;i++){ ptr[i]='A';}
Why does it occur?
Writing beyond allocated size.
Writing beyond allocated size.
Symptoms
- Random crashes far from actual bug
- malloc()/new failures
- Random crashes far from actual bug
- malloc()/new failures
Solution
- Bounds checking
- AddressSanitizer
- Smart containers
- Bounds checking
- AddressSanitizer
- Smart containers
11. Memory Fragmentation
What is it?
Available memory exists but is split into many small blocks.
Available memory exists but is split into many small blocks.
Example
Repeated allocation/deallocation:
newdeletenewdelete
Repeated allocation/deallocation:
Why does it occur?
Dynamic allocation patterns.
Dynamic allocation patterns.
Symptoms
- Allocation failures
- Slow performance
- Allocation failures
- Slow performance
Solution
- Memory pools
- Object pools
- Custom allocators
Common in embedded systems.
- Memory pools
- Object pools
- Custom allocators
Common in embedded systems.
12. Out Of Memory (OOM)
What is it?
Application requests more memory than available.
Application requests more memory than available.
Example
while(true){ new char[1024*1024];}
Symptoms
- Allocation failure
- System slowdown
- Process termination
- Allocation failure
- System slowdown
- Process termination
Solution
Check allocation results.
try{ auto data = new int[1000000];}catch(std::bad_alloc&){}
Check allocation results.
13. Race Condition on Shared Memory
What is it?
Multiple threads access the same memory simultaneously.
Multiple threads access the same memory simultaneously.
Example
int counter = 0;Thread1: counter++;Thread2: counter++;
Why does it occur?
Lack of synchronization.
Lack of synchronization.
Symptoms
- Random failures
- Incorrect data
- Random failures
- Incorrect data
Solution
std::mutexor
std::atomic<int>
or
14. Memory Alignment Issues
What is it?
CPU requires data to be aligned at specific addresses.
CPU requires data to be aligned at specific addresses.
Example
Common in ARM processors and embedded systems.
Common in ARM processors and embedded systems.
Symptoms
- Bus Error
- Performance degradation
- Bus Error
- Performance degradation
Solution
Use proper alignment.
alignas(8)struct Data{};
Use proper alignment.
15. Reading Uninitialized Memory
What is it?
Program reads memory before assigning a value.
Program reads memory before assigning a value.
Example
int x;cout << x;
Symptoms
- Random values
- Unpredictable behavior
- Random values
- Unpredictable behavior
Solution
Initialize everything.
int x = 0;
Initialize everything.
Tools Used to Detect Memory Issues
AddressSanitizer (Recommended)
Compile:
g++ -fsanitize=address -g main.cppDetects:
- Use After Free
- Buffer Overflow
- Heap Corruption
- Double Free
Compile:
Detects:
- Use After Free
- Buffer Overflow
- Heap Corruption
- Double Free
UndefinedBehaviorSanitizer
g++ -fsanitize=undefinedDetects:
- Invalid pointer usage
- Integer overflow
- Undefined behavior
Detects:
- Invalid pointer usage
- Integer overflow
- Undefined behavior
Valgrind
valgrind --tool=memcheck ./appDetects:
- Memory leaks
- Invalid reads/writes
- Use-after-free
Detects:
- Memory leaks
- Invalid reads/writes
- Use-after-free
GDB
gdb ./app coreUseful for:
- Segmentation faults
- Stack traces
- Core dump analysis
Useful for:
- Segmentation faults
- Stack traces
- Core dump analysis
Best Practices to Avoid Memory Errors
✅ Prefer std::vector over arrays
✅ Prefer std::string over character buffers
✅ Use std::unique_ptr and std::shared_ptr
✅ Initialize all pointers and variables
✅ Perform boundary checks on arrays
✅ Enable compiler warnings (-Wall -Wextra -Wpedantic)
✅ Use AddressSanitizer during development
✅ Run static analysis tools (clang-tidy, cppcheck)
✅ Follow RAII (Resource Acquisition Is Initialization) principles
✅ Review ownership of dynamically allocated memory
✅ Prefer std::vector over arrays
✅ Prefer std::string over character buffers
✅ Use std::unique_ptr and std::shared_ptr
✅ Initialize all pointers and variables
✅ Perform boundary checks on arrays
✅ Enable compiler warnings (-Wall -Wextra -Wpedantic)
✅ Use AddressSanitizer during development
✅ Run static analysis tools (clang-tidy, cppcheck)
✅ Follow RAII (Resource Acquisition Is Initialization) principles
✅ Review ownership of dynamically allocated memory
Summary Table
Error Type Cause Result Recommended Fix Null Pointer Invalid pointer Crash Check for nullptr Wild Pointer Uninitialized pointer Random behavior Initialize pointer Dangling Pointer Object destroyed Crash Avoid invalid references Use After Free Access freed memory Crash Smart pointers Double Free Memory freed twice Heap corruption Ownership control Buffer Overflow Writing outside bounds Crash/Security issue Bounds checking Stack Overflow Excessive recursion Crash Limit recursion Memory Leak Memory never freed RAM exhaustion RAII Heap Corruption Overwrite heap memory Random crashes Sanitizers Race Condition Concurrent access Data corruption Mutex/Atomic Uninitialized Memory Value not assigned Random output Initialize variables
Golden Rule: Modern C++ (C++11 and later) significantly reduces memory-related bugs when you use RAII, smart pointers, STL containers (vector, string, array), sanitizers, and static analysis tools instead of manual memory management.
Related Links :
| Error Type | Cause | Result | Recommended Fix |
|---|---|---|---|
| Null Pointer | Invalid pointer | Crash | Check for nullptr |
| Wild Pointer | Uninitialized pointer | Random behavior | Initialize pointer |
| Dangling Pointer | Object destroyed | Crash | Avoid invalid references |
| Use After Free | Access freed memory | Crash | Smart pointers |
| Double Free | Memory freed twice | Heap corruption | Ownership control |
| Buffer Overflow | Writing outside bounds | Crash/Security issue | Bounds checking |
| Stack Overflow | Excessive recursion | Crash | Limit recursion |
| Memory Leak | Memory never freed | RAM exhaustion | RAII |
| Heap Corruption | Overwrite heap memory | Random crashes | Sanitizers |
| Race Condition | Concurrent access | Data corruption | Mutex/Atomic |
| Uninitialized Memory | Value not assigned | Random output | Initialize variables |
Golden Rule: Modern C++ (C++11 and later) significantly reduces memory-related bugs when you use RAII, smart pointers, STL containers (vector, string, array), sanitizers, and static analysis tools instead of manual memory management.
Related Links :
Comments
Post a Comment