6.19.17 free Function

Frees dynamically allocated memory.

Include

<stdlib.h>

Prototype

void free(void * ptr);

Argument

ptr
pointer to the memory to be freed

Remarks

Frees memory previously allocated with calloc, malloc or realloc. If free is used on space that has already been deallocated (by a previous call to free or by realloc) or on space not allocated with calloc, malloc or realloc, the behavior is undefined.

When using the simple implementation of dynamic memory allocation, only a rudimentary merging of freed memory blocks is performed. See your MPLAB XC compiler User's Guide for more information on how dynamic memory allocation is implemented with your compiler.

Example

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  long *i;

  if ((i = (long *)malloc(50 * sizeof(long))) == NULL)
    printf("Cannot allocate memory\n");
  else
  {
    printf("Memory allocated\n");
    free(i);
    printf("Memory freed\n");
  }
}

Example Output

Memory allocated
Memory freed