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.

1. Null Pointer Dereference

What is it?

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

Symptoms

  • Segmentation Fault
  • Access Violation

Solution

Always validate pointers before use.

if(ptr != nullptr)
{
    *ptr = 10;
}

Use smart pointers when possible.


2. Wild Pointer (Uninitialized Pointer)

What is it?

A pointer contains garbage data because it was never initialized.

Example

int *ptr;
*ptr = 10;   // Undefined behavior

Why does it occur?

Developer forgets initialization.

Symptoms

  • Random crashes
  • Memory corruption
  • Intermittent bugs

Solution

Initialize pointers immediately.

int *ptr = nullptr;

or

int value;
int *ptr = &value;


3. Dangling Pointer

What is it?

Pointer points to memory that no longer exists.

Example

int* GetValue()
{
    int x = 5;
    return &x;
}

After function exits, x is destroyed.

Why does it occur?

  • Returning local variable address
  • Object destroyed
  • Memory freed

Symptoms

  • Random crashes
  • Incorrect values

Solution

Never return addresses of local variables.

int GetValue()
{
    int x = 5;
    return x;
}


4. Use After Free

What is it?

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

Symptoms

  • 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);


5. Double Free

What is it?

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

Symptoms

  • Heap corruption
  • Program crashes

Solution

delete ptr;
ptr = nullptr;

Use RAII and smart pointers.

std::unique_ptr<int>


6. Buffer Overflow

What is it?

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

Symptoms

  • Stack corruption
  • Random crashes
  • Security exploits

Solution

Use size-limited functions.

strncpy(name, input, sizeof(name)-1);

Or use:

std::string


7. Buffer Underflow

What is it?

Accessing memory before beginning of buffer.

Example

int arr[10];
arr[-1] = 5;

Why does it occur?

Incorrect indexing.

Symptoms

  • Data corruption
  • Crashes

Solution

Validate indexes.

if(index >= 0 &&
   index < size)
{
    arr[index] = value;
}


8. Stack Overflow

What is it?

Program consumes more stack memory than available.

Example

Infinite recursion:

void Func()
{
    Func();
}

Why does it occur?

  • Infinite recursion
  • Huge local arrays

Symptoms

  • Stack Smashing
  • Segmentation Fault

Solution

Limit recursion depth.

Avoid large stack variables.

std::vector<int> data(1000000);

Use heap memory for large data.


9. Memory Leak

What is it?

Allocated memory is never released.

Example

void Func()
{
    int *ptr = new int[100];
}

Memory lost after function exits.

Why does it occur?

Forgot to call delete.

Symptoms

  • Increasing RAM usage
  • Slow system
  • Out-of-memory errors

Solution

delete[] ptr;

Best approach:

std::vector<int>
std::unique_ptr


10. Heap Corruption

What is it?

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.

Symptoms

  • Random crashes far from actual bug
  • malloc()/new failures

Solution

  • Bounds checking
  • AddressSanitizer
  • Smart containers

11. Memory Fragmentation

What is it?

Available memory exists but is split into many small blocks.

Example

Repeated allocation/deallocation:

new
delete
new
delete

Why does it occur?

Dynamic allocation patterns.

Symptoms

  • Allocation failures
  • Slow performance

Solution

  • Memory pools
  • Object pools
  • Custom allocators

Common in embedded systems.


12. Out Of Memory (OOM)

What is it?

Application requests more memory than available.

Example

while(true)
{
    new char[1024*1024];
}

Symptoms

  • Allocation failure
  • System slowdown
  • Process termination

Solution

Check allocation results.

try
{
    auto data = new int[1000000];
}
catch(std::bad_alloc&)
{
}


13. Race Condition on Shared Memory

What is it?

Multiple threads access the same memory simultaneously.

Example

int counter = 0;
Thread1: counter++;
Thread2: counter++;

Why does it occur?

Lack of synchronization.

Symptoms

  • Random failures
  • Incorrect data

Solution

std::mutex

or

std::atomic<int>


14. Memory Alignment Issues

What is it?

CPU requires data to be aligned at specific addresses.

Example

Common in ARM processors and embedded systems.

Symptoms

  • Bus Error
  • Performance degradation

Solution

Use proper alignment.

alignas(8)
struct Data
{
};


15. Reading Uninitialized Memory

What is it?

Program reads memory before assigning a value.

Example

int x;
cout << x;

Symptoms

  • Random values
  • Unpredictable behavior

Solution

Initialize everything.

int x = 0;


Tools Used to Detect Memory Issues

AddressSanitizer (Recommended)

Compile:

g++ -fsanitize=address -g main.cpp

Detects:

  • Use After Free
  • Buffer Overflow
  • Heap Corruption
  • Double Free

UndefinedBehaviorSanitizer

g++ -fsanitize=undefined

Detects:

  • Invalid pointer usage
  • Integer overflow
  • Undefined behavior

Valgrind

valgrind --tool=memcheck ./app

Detects:

  • Memory leaks
  • Invalid reads/writes
  • Use-after-free

GDB

gdb ./app core

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

Summary Table

Error TypeCauseResultRecommended Fix
Null PointerInvalid pointerCrashCheck for nullptr
Wild PointerUninitialized pointerRandom behaviorInitialize pointer
Dangling PointerObject destroyedCrashAvoid invalid references
Use After FreeAccess freed memoryCrashSmart pointers
Double FreeMemory freed twiceHeap corruptionOwnership control
Buffer OverflowWriting outside boundsCrash/Security issueBounds checking
Stack OverflowExcessive recursionCrashLimit recursion
Memory LeakMemory never freedRAM exhaustionRAII
Heap CorruptionOverwrite heap memoryRandom crashesSanitizers
Race ConditionConcurrent accessData corruptionMutex/Atomic
Uninitialized MemoryValue not assignedRandom outputInitialize 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

Popular posts from this blog

Setting up a USB thermal printer with a Raspberry Pi 3B+

Create a autorun for a PyQt5 raspberry pi Application

Basic Input/Output C Program