malloc ¶When you no longer need a block that you got with malloc, use the
function free to make the block available to be allocated again.
The prototype for this function is in stdlib.h.
void free (void *ptr) ¶Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.
The free function deallocates the block of memory pointed at
by ptr.
Freeing a block alters the contents of the block. Do not expect to find any data (such as a pointer to the next block in a chain of blocks) in the block after freeing it. Copy whatever you need out of the block before freeing it! Here is an example of the proper way to free all the blocks in a chain, and the strings that they point to:
struct chain
{
struct chain *next;
char *name;
}
void
free_chain (struct chain *chain)
{
while (chain != 0)
{
struct chain *next = chain->next;
free (chain->name);
free (chain);
chain = next;
}
}
Occasionally, free can actually return memory to the operating
system and make the process smaller. Usually, all it can do is allow a
later call to malloc to reuse the space. In the meantime, the
space remains in your program as part of a free-list used internally by
malloc.
The free function preserves the value of errno, so that
cleanup code need not worry about saving and restoring errno
around a call to free. Although neither ISO C nor
POSIX.1-2017 requires free to preserve errno, a future
version of POSIX is planned to require it.
There is no point in freeing blocks at the end of a program, because all of the program’s space is given back to the system when the process terminates.
void free_sized (void *ptr, size_t size) ¶Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.
The free_sized function deallocates the block of memory pointed at
by ptr that was previously allocated by malloc, calloc
or realloc. The size size must match the previously requested
total size provided to malloc, calloc or realloc.
Attempting to deallocated memory allocated by aligned_alloc,
memalign, posix_memalign, valloc or pvalloc is
undefined behavior. For aligned_alloc, memalign or
posix_memalign use free_aligned_sized instead. Additionally
it is also undefined behavior to call free_sized for allocations
which the caller did not directly allocate but must still deallocate, such
as the result of strdup or strndup. Instead continue using
free for these cases.
void free_aligned_sized (void *ptr, size_t alignment, size_t size) ¶Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.
The free_aligned_sized function deallocates the block of memory
pointed at by ptr that was previously allocated by
aligned_alloc, memalign or posix_memalign.
The size size and alignment alignment must match the
previously requested size and alignment provided to
aligned_alloc, memalign or posix_memalign.