Skip to content

Latest commit

 

History

History
51 lines (31 loc) · 2.36 KB

CppStdRealloc.md

File metadata and controls

51 lines (31 loc) · 2.36 KB

 

 

 

 

 

 

std::realloc is an STL function used in C-style memory management:

 

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); }