std::realloc is an STL function used in C-style memory management:
- std::malloc: allocates memory
- std::realloc: reallocates memory
- std::free: releases memory
Prefer to use the C++ keyword new over std::malloc, as std::malloc does not call a constructor. Prefer to use the C++ keyword delete over std::free, as std::free does not call a destructor.
#include <cassert> #include <cstdlib> int main() { const int size = 100; //Create a dynamically allocated array int * my_array = static_cast<int*>(std::malloc(size * sizeof(int))); //Assume the memory for the array could be allocated assert(my_array); const int new_size = 200; //Resize the array my_array = static_cast<int*>(std::realloc (my_array, new_size * sizeof(int))); //Assume the memory for the array could be allocated assert(my_array); //Free the array std::free(my_array); }