MCN Professionals | Interview Question of the day
|
Date: 5th
Sept; 2011
|
Difficulty Level: ***
|
Category: Programming
|
|
To receive one
interview question in your mailbox daily, please subscribe to "A
Question A Day" at MCN Professionals home page.
|
Today's Question:
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.
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.. 
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;
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;
Interview Questions Archive:
To see all the questions in the category, click here...
------------------------------------------------------------------------------------------------------------