Dynamic Memory Allocation in C++

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.



Hiran Kodithuwakku

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] )

要查看或添加评论,请登录

Kajanthan sureshkumar的更多文章

社区洞察

其他会员也浏览了