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

  1. Memory leaks: If you forget to delete memory that was allocated using new, it will remain allocated until the program terminates, leading to a memory leak.
  2. Dangling pointers: If you delete a pointer that was not allocated using new, or if you delete a pointer that has already been deleted, you will get a dangling pointer, which can lead to undefined behavior.
  3. Smart pointers: C++11 introduced smart pointers, such as unique_ptr and shared_ptr, which can help manage memory automatically and avoid common pitfalls like memory leaks and dangling pointers.

Best practices

  1. Use new and delete sparingly, and only when necessary.
  2. Use smart pointers whenever possible.
  3. Always delete memory that was allocated using new.
  4. 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.