The free function deallocates a block of memory that has been previously allocated using the malloc function. The free function takes only one argument as input, a pointer to the memory block that will be freed.

The function free has undefined behavior if the address passed as a parameter does not pointer to a valid, heap allocated, block returned by the malloc function. Always make sure you are passing a valid memory address to free.

Accessing memory that has been passed to free

A common problem happens when memory that has been freed is accessed again. If this happens, the result is undefined, since any memory that has been freed can be reused by the program to other purposes. To avoid such invalid accesses, it is common to assign NULL to a pointer that has been recently sent to the free function.

The following code shows an example of free in use:

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

int main()
        int i;
        int num_elements = 10;
        int *p;
        p = (int *)malloc(sizeof(int)*10);
        return 0;
Article created on 2008-08-19 21:57:00

Post a comment