free(i); // freed the mem
*i=50; // Tried to acces it again .. Ideally , it should 
fail . But it is not failing .. can any //one explain the 
reason.

After you've freed memory, you must not rely on it still 
being available. It might be available but it might not, 
depending on how the memory manager (malloc/free) is 
working.

When you allocate memory, that chunk of memory is marked as 
not being available for any other purpose. When you free it, 
that marking is removed. A very aggressive memory manager 
might immediately allocate it elsewhere or return it to the 
operating system (unlikely), but most memory managers will 
just leave it alone.

Freeing amounts to saying "I don't care what you do with 
that area of memory now, I won't be using it again."

It's a bit like files on a disk drive. When you "delete" a 
file, all you do is tell the file system that you aren't 
interested in that data any more. The data is allowed to be 
overwritten, but, as many people have found to their cost, 
it often isn't, and the "deleted" file can sometimes be 
successfully recovered in its entirety.

If you want to make sure your data isn't available after 
freeing memory, you should overwrite it before freeing it. 
(E.g. using memset.) It's also a good idea to make a 
practice of setting the related pointer to NULL, like this:

  p = malloc(whatever);
  /* use the allocated memory */
  free(p), p = NULL;

Then if you mistakenly try to use p later on, you'll get a 
segmentation fault. This is likely to be noticed, whereas 
using memory that doesn't belong to you may go unpunished 
for quite a long time.

David

Reply via email to