free
Defined in header
<stdlib.h>
|
||
void free( void* ptr );
|
||
Deallocates the space previously allocated by malloc(), calloc() or realloc(). If ptr
is null-pointer, the function does nothing.
The behavior is undefined if ptr
does not match a pointer returned earlier by malloc(), calloc(), realloc(), or aligned_alloc(). Also, the behavior is undefined if the memory area referred to by ptr
has already been deallocated, that is, free()
or realloc() has already been called with ptr
as the argument and no calls to malloc(), calloc() or realloc() resulted in a pointer equal to ptr
afterwards.
A call to free that deallocates a region of memory synchronizes-with a call to any subsequent allocation function that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by the allocation function. |
(since C11) |
Contents |
[edit] Parameters
ptr | - | pointer to the memory to deallocate |
[edit] Return value
(none)
[edit] Example
This section is incomplete Reason: simplify or make more practical |
#include <stdio.h> #include <stdlib.h> int main(void) { /* Allocate an array with 100 integers. */ int *pa = malloc(100*sizeof(int)); if (pa == NULL) { /* check that memory allocation occurred */ printf("malloc() failed in file %s at line # %d", __FILE__,__LINE__); printf("*** PROGRAM TERMINATED ***"); exit(1); } printf("starting address of pa: %p\n", (void*)pa); /* Deallocate array pa. */ free(pa), pa = NULL; /* Allocate an array with 100 doubles. */ double *pb = malloc(100*sizeof(double)); if (pb == NULL) { /* check that memory allocation occurred */ printf("malloc() failed in file %s at line # %d", __FILE__,__LINE__); printf("*** PROGRAM TERMINATED ***"); exit(1); } /* Array pb may have the same starting address that array pa had. */ printf("starting address of pb: %p\n", (void*)pb); free(pb); return 0; }
Possible output:
starting address of pa: 0x2113010 starting address of pb: 0x2113010
[edit] See also
C++ documentation for free
|