Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::free

 

std::free 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);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict