Jun 132012
 

Yesterday we learned about how to allocate memory on heap for an n-dim array using Malloc.

Today let us see how to deallocate the memory on heap using free. It is Simple if we are deallocating normal pointers or pointers pointing to a one-dimensional array.

How will deallocate memory of an n-dim array on heap?

Solution:

Remember the way constructors & destructor are called in C++? The process of deallocating a memory is reverse of the way we allocate it.

Deallocating 1-Dimension Array:

For a one-dim array it is simply a call to function free and then assigning NULL to the pointer.

    free(p);
    p = NULL;

The assignment to NULL is very important. It may otherwise make p a dangling pointer (a pointer which holds the address of memory location that is freed to the compiler). You should also note that some other pointer should not become dangling in this process. For example consider the below case:

    int *p = (int*) malloc(sizeof(int));
    int *q = p;

If we free the p pointer like

    free(p);
    p = NULL;

Though we deallocate p properly, we make q dangling in the process..

Deallocating 2-Dimensional Array

To deallocate a 2-dim array, you have to deallocate each element of one dimension array (the array pointing to the arrays of ints) before deallocating the pointer pointing to the 2-dim array. Else you will loose the address of smaller arrays.

    for(int i=0; i<m; i++)
        free(p[i]);

    free(p);
    p = NULL;

Deallocating n-dim array

Note that we didn’t assign NULL to individual p[i] elements. This is because they will be deallocated in the very next statement. You may do that if you want to on the cost of one necessary operation.

Lets take the last example of deallocating a 3-dim array:

    for(int i =0; i<A; i++)
        for(int j=0; j<B; j++)
            free(p[i][j]); 

    for(int i=0; i<A; i++)
        free(p[i]);

    free(p);
    p = NULL;

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)