Namespaces
Variants
Views
Actions

free

From cppreference.com
< c‎ | memory
Revision as of 12:08, 4 February 2014 by P12 (Talk | contribs)

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() or realloc(). 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.

Contents

Parameters

ptr - pointer to the memory to deallocate

Return value

(none)

Example

#include <stdio.h>
#include <stdlib.h>
 
int main() 
{
    /* 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 A:   0x2113010
starting address of B:   0x2113010

See also