C++ Dynamic Memory Management | new, delete, RAII, Memory Leaks and malloc vs new
This complete tutorial on C++ Dynamic Memory Management explains how to allocate and deallocate memory at runtime using new, delete, new[], and delete[]. It also covers malloc vs new, memory leaks, and the RAII concept for safe memory handling. Following best practices, it helps learners write efficient and safe C++ programs.
Dynamic Memory Management – Complete Tutorial
1. What is Dynamic Memory Management?
Dynamic memory management allows allocating memory at runtime, instead of fixed memory at compile time.
- Useful for objects whose size is unknown during compilation
- Memory must be manually managed to avoid leaks
2. new and delete
newallocates memory for a single objectdeletefrees memory allocated bynew
Example:
3. new[] and delete[]
Used for dynamic arrays.
Example:
Key Points:
- Always use
delete[]for arrays allocated withnew[] - Avoid mismatched
delete/delete[]
4. malloc vs new
| Featuremallocnew | ||
| Header | <cstdlib> | none |
| Type Safety | No | Yes |
| Constructor | Not called | Called |
| Returns | void* | Object pointer |
| Free Memory | free() | delete |
Best Practice: Prefer new and delete in C++ because they handle constructors/destructors automatically.
5. Memory Leaks
Memory leaks occur when dynamically allocated memory is not freed.
Example:
How to Avoid:
- Always pair
newwithdeleteandnew[]withdelete[] - Use smart pointers (
std::unique_ptr,std::shared_ptr) - Set pointers to
nullptrafter deletion
6. RAII Concept (Resource Acquisition Is Initialization)
RAII ensures resources are automatically released when objects go out of scope.
Example with smart pointer:
Key Points:
- Prevents memory leaks
- Ensures automatic cleanup of resources
- Use smart pointers in modern C++
Best Practices
- Always delete dynamically allocated memory
- Use
nullptrafter deletion - Prefer smart pointers for automatic memory management
- Avoid excessive dynamic allocation if possible
- Follow RAII principles for robust resource management
Common Mistakes
- Forgetting to free memory → memory leak
- Using memory after deletion → dangling pointer
- Mixing
mallocwithdeleteornewwithfree - Not handling exceptions that may bypass
delete
Summary
In this chapter, you learned about C++ Dynamic Memory Management, including:
newanddeletefor single objectsnew[]anddelete[]for arrays- Difference between
mallocandnew - Memory leaks and how to avoid them
- RAII and smart pointers for safe memory handling
Dynamic memory management is essential for efficient C++ programming, especially for large programs and real-world applications.