C++ new delete
A fundamental topic in C++!
new
and delete
are operators in C++ that are used to dynamically allocate and deallocate memory.
new
operator
The new
operator is used to dynamically allocate memory for an object or an array. It returns a pointer to the allocated memory.
Syntax: new type
or new type[size]
Example:
int* p = new int; // allocate memory for a single int
int* arr = new int[5]; // allocate memory for an array of 5 ints
When you use new
, the memory is allocated on the heap, and the pointer returned by new
is the starting address of the allocated memory.
delete
operator
The delete
operator is used to deallocate memory that was previously allocated using new
. It takes a pointer to the memory to be deallocated as an argument.
Syntax: delete ptr
or delete[] ptr
Example:
delete p; // deallocate memory for a single int
delete[] arr; // deallocate memory for an array of 5 ints
When you use delete
, the memory is released back to the heap, and the pointer becomes invalid.
Important notes
- Memory leaks: If you forget to
delete
memory that was allocated usingnew
, it will remain allocated until the program terminates, leading to a memory leak. - Dangling pointers: If you
delete
a pointer that was not allocated usingnew
, or if youdelete
a pointer that has already been deleted, you will get a dangling pointer, which can lead to undefined behavior. - Smart pointers: C++11 introduced smart pointers, such as
unique_ptr
andshared_ptr
, which can help manage memory automatically and avoid common pitfalls like memory leaks and dangling pointers.
Best practices
- Use
new
anddelete
sparingly, and only when necessary. - Use smart pointers whenever possible.
- Always
delete
memory that was allocated usingnew
. - Avoid using raw pointers (e.g.,
int* p
) whenever possible; instead, use smart pointers or containers that manage memory for you.
By following these best practices, you can write more robust and maintainable C++ code that manages memory effectively.