std::free

From cppreference.com
< cpp‎ | memory‎ | c
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
Defined in header <cstdlib>
void free( void* ptr );

Deallocates the space previously allocated by std::malloc(), std::calloc() or std::realloc().

If ptr is a null pointer, the function does nothing.

The behavior is undefined if the value of ptr does not equal a value returned earlier by std::malloc(), std::calloc(), or std::realloc().

The behavior is undefined if the memory area referred to by ptr has already been deallocated, that is, std::free() or std::realloc() has already been called with ptr as the argument and no calls to std::malloc(), std::calloc() or std::realloc() resulted in a pointer equal to ptr afterwards.

The behavior is undefined if after std::free() returns, an access is made through the pointer ptr (unless another allocation function happened to result in a pointer value equal to ptr)

Contents

[edit] Parameters

ptr - pointer to the memory to deallocate

[edit] Return value

(none)

[edit] Notes

The function accepts (and does nothing with) the null pointer to reduce the amount of special-casing. Whether allocation succeeds or not, the pointer returned by an allocation function can be passed to free()

[edit] Example

#include <cstdlib>
 
int main()
{
    int* p1 = (int*)std::malloc(10*sizeof *p1);
    std::free(p1); // every allocated pointer must be freed
 
    int* p2 = (int*)std::calloc(10, sizeof *p2);
    int* p3 = (int*)std::realloc(p2, 1000*sizeof *p3);
    if(p3) // p3 not null means p2 was freed by std::realloc
       std::free(p3);
    else // p3 null means p2 was not freed
       std::free(p2);
}


[edit] See also

C documentation for free