Modern C++
    Language Concepts
    Smart Pointers
    Memory Management
    Type Casting
    Trouble Shooting

C / C++ - Memory Management

Updated: 2022-03-26

C++: new / delete

Use keywords new and delete, or smart pointers.

Read more: Smart Pointers

char *pBuffer = new char[1024];
delete[] pBuffer;

new vs malloc


  • You cannot mix new / free and malloc / delete.
  • in C++, don't use malloc for C++ without a really good reason

new is more type-safe; malloc is not typesafe in any meaningful way. In C++ you are required to cast the return from void*.

Foo *f1 = malloc(1); // error, no cast
Foo *f2 = static_cast<Foo*>(malloc(sizeof(Foo)));

malloc returns NULL if allocation fails. new will throw std::bad_alloc.

int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements

Use malloc if you need to change the size of your buffer of data. realloc can be used to extend the size of a chunk of memory.

C: malloc() / calloc() / free()

Use functions malloc() / calloc() and free().


malloc() = memory allocation

It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.


ptr = (int*) malloc(100 * sizeof(int));


calloc() = contiguous allocation, allocate the specified number of blocks of memory of the specified type.

void *calloc(size_t nitems, size_t size)


int* a = (int*) calloc(5, sizeof(int));

calloc() vs malloc()

  • malloc() does not set the memory to zero, calloc() sets allocated memory to zero.
  • malloc() has one parameter, calloc() has two.


ptr = realloc(ptr, newSize);

The function returns a void pointer to this memory location, which can then be cast to the desired type.


Free the memory when it is no longer used.