Pointers/Memory Allocation   «Prev  Next»
Lesson 8 Free store operators
Objective Understand the use of the free store operators new and delete.

C++ Free Store Operators

In C++, the `new` and `delete` operators are used to manage dynamic memory allocation on the free store (heap).
  1. `new` Operator**: Allocates memory for a variable or object dynamically. It returns a pointer to the allocated memory. Syntax:
    int* ptr = new int;  // Allocates memory for an integer
    
  2. `delete` Operator**: Deallocates memory that was previously allocated using `new`. It frees up the allocated space. Syntax:
    delete ptr;  // Frees the memory allocated to ptr
    

For arrays, use `new[]` and `delete[]`. Proper use of these operators is crucial to avoid memory leaks.

C++ Operators new delete

The operators new and delete access heap storage and are built into the language.
They are to be preferred to the older C library functions malloc() and free(), which do not automatically understand the C++ types they are working with. Heap allocation that fails will result in either an allocation exception being thrown or a return value of 0 as a pointer expression indicating failure. Assertions or catches can be used as a postcondition to test whether heap allocation succeeded. These errors are system-dependent and should be routinely tested for at runtime.
void* operator new[] (std::size_t size) throw (std::bad_alloc);
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void* operator new[] (std::size_t size, void* ptr) throw();

  • Allocate storage space for array:
    The first version allocates size bytes of storage space, aligned to represent an array object of that size (or less, if the implementation uses array overhead), and returns a non-null pointer to the first byte of this block. On failure, it throws a bad_alloc exception. The second version is the nothrow version. It does the same as the first version, except that on failure it turns a null pointer instead of throwing an exception. The third version is the placement version, that does not allocate memory, but simply returns ptr. Notice though that the constructor for the object will still be called.
    Global dynamic storage operator functions are special in the standard library:
    1. All three versions of operator new[] are declared in the global namespace, not in the std namespace.
    2. The first and second versions are implicitly declared in every translation unit of a C++ program: The header <new> does not need to be included for them to be present.
    3. The first and second versions are also replaceable: A program may provide its own definition, that replaces the default one, to produce the result described above.


The unary operators new and delete are available to manipulate free store, which is a system-provided memory pool for variables whose lifetime is directly managed by the programmer. You create the variable by using new and destroy the object by using delete. Manipulating free store memory is important for dynamic data structures such as lists and trees. We will look at new and delete in the next two lessons. In order to request dynamic memory we use the operator new. new is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is:
pointer = new type
pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one single element of type type.
The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these.

C++ How to Program
  • new() operator: The new operator allocates memory from an area called the free store (also known as dynamic memory and heap). Objects allocated on the free store are independent of the scope from which they are created and "live" until they are destroyed using the delete operator. Vector's constructor allocates some memory on the free store using the new operator.
    Class hierarchies are different: we tend to allocate them on the free store using new, and we access them through pointers or references. In addition to the initialization of named objects and objects on the free store, constructors are used to initialize temporary objects and to implement explicit type conversion.
  • Heap Memory: There are many situations where stack memory is inappropriate. It is often difficult or impossible to estimate beforehand how large an object should be. For example, how many elements an array needs to contain. It may also be difficult to determine how many items a program might require. For example, how many nodes will be contained in a linked list. Finally, it is also common that the lifetime of a value is not tied to procedure entry and exit. For example, when a value is placed into a linked list, the value will continue to exist even after the insertion function finishes execution. In such cases, local variables on the stack cannot be used, and dynamic allocation of storage is necessary. The heap or free store is the storage area for values explicitly requested using the new operator.
    Employee* boss = new Employee("Lin, Lisa", 68000);
    
  • this operator: When you ask for a section of memory using this operator, a memory allocator finds a storage location for the new object in the heap. The memory allocator tells you where the object is located by returning the memory address for the value. This is termed dynamic memory allocation. Dynamically allocated values are accessed through a pointer, which itself might reside either on the stack or on the heap. The statement above declares a pointer variable named boss that resides on the stack. The value of the pointer references a data area stored on the heap. Once you are finished with the dynamically allocated memory you must notify the memory allocator that it can be returned to the free store. This is done using the delete operator:
    delete boss;
    

    This statement deletes the heap memory that variable boss refers to.


SEMrush Software