Dynamic Memory Management

📘 C++ 👁 37 views 📅 Dec 22, 2025
⏱ Estimated reading time: 1 min

Dynamic memory management allows a program to allocate and deallocate memory at runtime.


Why Dynamic Memory is Needed

  • Size of data not known at compile time

  • Efficient use of memory

  • Supports dynamic data structures


Operators Used

C++ provides two operators:

  • new

  • delete


Allocating Memory Using new

Single Variable

int *ptr = new int;

Array Allocation

int *arr = new int[5];

Initializing Dynamic Memory

int *ptr = new int(10);

Deallocating Memory Using delete

Single Variable

delete ptr;

Array

delete[] arr;

Example Program

#include using namespace std; int main() { int *ptr = new int(20); cout << *ptr; delete ptr; return 0; }

Memory Leak

Occurs when allocated memory is not released.

int *p = new int; // delete p; // Missing delete causes memory leak

Advantages

  • Memory used only when required

  • Improves program flexibility

  • Efficient memory usage


Key Points

  • new allocates memory

  • delete frees memory

  • Use delete[] for arrays

  • Avoid memory leaks


Conclusion

Dynamic memory management in C++ provides control over memory usage and is essential for efficient program execution.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes