Sachin wrote:
int *p, *q, temp=2;
p = (int*) malloc (sizeof(int));
Better: p = malloc(sizeof *p); /* but WHY malloc a single int? */
The reason it's better to drop the cast is that it can hide the
bug of failing to #include <stdlib.h> to get a prototype for
malloc.
q = p;
*p = temp;
Oops. You used *p without checking whether p is NULL. malloc /can/ fail.
free (p);
printf ("%d",*q);
In the above code, what will be the output and why?
The output, if any, is undefined, as is the behaviour of the program
from this point on.
And also explain
what exactly happens to 'p' and 'q' once 'p' is freed.
Once p is freed, its value (which q shares, because of q = p;) is
indeterminate. It might have the same bit pattern as before, but that
is irrelevant. The *meaning* of p has changed from "points to a block
to which the program has permission to use" to "does not point to
anywhere special, and certainly not to a block that the program has
permission to use". Because q = p, the meaning of q has changed too.
Using a block after you freed it invokes consequences that the C
language definition shies away from; all bets are off, and there
is no way to predict correctly what this program will do. You
might take a guess, and you might even be right, but you cannot
*know* what the program will do (from the language definition
perspective), because it has become meaningless.