SoFunction
Updated on 2025-05-22

How to use memory allocation new and delete in C++

C++ new and delete

In C++,newanddeleteIs an operator for dynamic memory allocation and release.

They allow programs to manage heap memory at runtime and are the basis for implementing dynamic data structures (such as linked lists, trees) and flexible resource management.

1. Basic syntax

new operator

  • Assign a single object
Type* ptr = new Type;         // Default initialization (built-in type value is not defined)Type* ptr = new Type(value);  // Direct initializationType* ptr = new Type{value};  // List initialization(C++11rise)
  • Allocation array
Type* arr = new Type[size];   // Assignment containssizeArray of elements
  • Value Initialization
Type* ptr = new Type();       // The value is initialized to0or default constructor

delete operator

  • Free a single object
delete ptr;  // Calling the destructor(If there is)and release memory
  • Free the array
delete[] arr;  // Free array memory,Need to use[]Tell the compiler to release multiple objects

2. Working principle

Execution steps for new

  • Memory allocation: Calledoperator new(oroperator new[]for arrays) allocate raw memory.
  • Constructor call: Call the object's constructor (if it is a class type) on the allocated memory.

The execution steps of delete

  • Destructor call: Call the destructor (if it is a class type) on the object.
  • Memory release: Calledoperator delete(oroperator delete[]) Free up memory.

3. Understand new and delete

Raw memory operations

operator newandoperator delete

The underlying function that can be overloaded to customize memory allocation behavior.

void* operator new(size_t size);      // Assign a single objectvoid* operator new[](size_t size);    // Allocation arrayvoid operator delete(void* ptr);      // Release a single objectvoid operator delete[](void* ptr);    // Free the array

Example

void* raw_memory = operator new(sizeof(int));  // Allocate raw memoryint* ptr = static_cast<int*>(raw_memory);      // Convert to an int pointer*ptr = 42;                                      // Manual assignmentoperator delete(ptr);                           // Free memory(Don't call the destructor)

Positioning new (Placement New)

Construct an object on the allocated memory:

void* buffer = operator new(sizeof(MyClass));  // Allocate raw memoryMyClass* obj = new (buffer) MyClass();         // Construct an object on a bufferobj->~MyClass();                               // explicitly call the destructoroperator delete(buffer);                       // Free memory

4. Dynamic allocation of arrays

Allocation and release arrays

int* arr = new int[10];       // Allocate an array of 10 intsdelete[] arr;                 // Free array
// Multidimensional arrayint** matrix = new int*[5];   // Assign 5 rowsfor (int i = 0; i < 5; ++i) {
    matrix[i] = new int[10];  // 10 columns per row}
// Releasefor (int i = 0; i < 5; ++i) {
    delete[] matrix[i];
}
delete[] matrix;

Array initialization

int* arr = new int[5]{1, 2, 3, 4, 5};  // C++11Support list initialization

When dynamically allocating an array, an additional piece of space will be automatically allocated before to store the number of space to be opened so that the space can be freed with delete in the future.

The implementation principle of delete

5.1 Built-in types

If you apply for a built-in type space, new and malloc, delete and free are basically similar, the differences are:

new/delete applies and releases space of a single element, new[] and delete[] apply for continuous space, and new will throw an exception when the application space fails, malloc will return NULL.

5.2 Custom Types

The principle of new

  • Call operator new function to apply for space
  • Execute the constructor on the application space to complete the object's construction

The principle of delete

  • Execute the destructor in space to complete the cleanup of resources in the object
  • Call the operator delete function to free up the object's space

The principle of new T[N]

  • Call the operator new[] function, and actually call the operator new function in the operator new[] to complete the application of N object spaces
  • Execute N constructors on the space of the application

The principle of delete[]

  • Execute N destructors on the freed object space to complete the cleaning of resources in N objects
  • Call operator delete[] to release space, and actually call operator delete in operator delete[] to free space

6. Frequently Asked Questions and Precautions

Memory leak

reason: Forgot to calldeletereleasenewAllocated memory.

Example

void leak() {
    int* ptr = new int;  // Allocate memory    // Return without freeing memory}  // Memory leak!

Hanging pointer

reason: After freeing memory, the pointer to that memory is still retained.

Example

int* ptr = new int;
delete ptr;
*ptr = 10;  // Dereference of hanging pointer,Undefined behavior

Repeat release

reason: Release the same piece of memory multiple times.

Example

int* ptr = new int;
delete ptr;
delete ptr;  // Repeat release,Undefined behavior

Mix delete and delete[]

Error Example

int* arr = new int[10];
delete arr;  // mistake!Should be useddelete[]

For built-in types, the program will crash; for custom types, the program will not crash.

7. Custom memory management

Overload global operator new and operator delete

void* operator new(size_t size) {
    void* p = malloc(size);
    // Can add memory allocation logs, performance monitoring, etc.    return p;
}

void operator delete(void* p) noexcept {
    free(p);
    // Memory release log can be added, etc.}

Class-specific memory management

class MyClass {
public:
    static void* operator new(size_t size) {
        // Custom allocation logic        return ::operator new(size);
    }
    
    static void operator delete(void* p) noexcept {
        // Custom release logic        ::operator delete(p);
    }
};

8. Comparison with C language memory management

characteristic C++ new/delete C language malloc/free
Type safety Automatically deduce types without casting Need to explicit conversion (such as (int*) malloc())
Constructor/destructor Automatically call constructors and destructors Don't call constructor/destructor
initialization Supports direct initialization and list initialization Only allocate memory, not initialize values
Array Syntax Use new Type[size] directly Total size needs to be calculated (such as malloc(size*sizeof(Type)))
Smart pointer support Seamlessly matched with standard library smart pointers Need to be manually encapsulated as smart pointers

The common point between malloc/free and new/delete is that both apply for space from the heap and needs to be manually released by the user.

The differences are:

  • malloc and free are functions, new and delete are operators
  • The space applied for malloc will not be initialized, new can be initialized
  • When malloc applies for space, it is necessary to manually calculate the space size and pass it. New only needs to be followed by the type of space. If it is multiple objects, specify the number of objects in []
  • The return value of malloc is void*, and must be strongly rotated when used. New does not need it because new is followed by the type of space.
  • When malloc fails to apply for space, it returns NULL, so it must be empty when used. New does not need it, but new needs to catch exceptions
  • When applying for a custom type object, malloc/free will only open up space and will not call constructors and destructors. After applying for space, new will call constructors to complete the initialization of the object. Before releasing the space, delete will call destructors to complete the cleaning and release of resources in the space.

Summarize

new/deleteIt is the core mechanism of C++ dynamic memory allocation, suitable for:

  • The object life cycle needs to be determined at runtime.
  • Implement dynamic data structures (such as linked lists and trees).
  • Priority to smart pointers: In modern C++,std::unique_ptrandstd::shared_ptrIt can effectively avoid memory leaks and improve code security.
  • Manually manage memory with caution: Must be surenewanddeleteUse paired to avoid hanging pointers and repeated releases.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.