Dynamic Memory Allocation in C++
Kajanthan sureshkumar
C++ Developer | R&D @SPIL Labs | Simulation Software Developer | Qt, MFC, OpenGL, Open CASCADE, Socket Programming
Dynamic memory allocation allows you to allocate memory at runtime, as your program needs it, rather than allocating all your memory up front. This is useful when you don't know how much memory you'll need ahead of time.In C++, dynamic memory allocation is typically done using the 'new' and 'delete' operators, or their array counterparts 'new[]' and 'delete[]'.
1.Allocation using 'new': The 'new' operator allocates memory for a single object at runtime and returns a pointer to that memory.
int *ptr = new int;
2.Allocation using 'new[]': The 'new[]' operator allocates memory for an array of elements at runtime and returns a pointer to the first element.
int *arr = new int[10];
3.Deallocation using 'delete': The 'delete' operator frees the memory that was previously allocated with 'new' for a single object.
delete ptr;
4.Deallocation using 'delete[]': The 'delete[]' operator frees memory that was previously allocated with 'new[]' for an array of elements.
delete[] arr;
Memory Leaks
A memory leak happens when dynamically allocated memory is not freed after it is no longer needed.
Software Engineer | BSc in Mechanical Engineering
1 年Even with dynamic memory allocation, you need to specify the size of the array (int *arr = new int[10] )