effect of free()

Conor P. Cahill cpcahil at virtech.UUCP
Tue Aug 15 13:30:44 AEST 1989


In article <320 at cubmol.BIO.COLUMBIA.EDU>, ping at cubmol.BIO.COLUMBIA.EDU (Shiping Zhang) writes:
> After I posted the question, I got many responces from both the network
> and e-mail. They certainly answered my original questions and clarified
> a lot of confusions I had. I am very grateful to all of them.
> 
> Now some new questions arises. Many people said that after free()
> is called, the point used as the argument to free() is still valid
> and can be used IF NO (mc)alloc()'s are called after the call to free().

It is not "valid" to use a pointer into "freed" space.  Under the right
conditions you will get away with it, but if you keep doing it long enough
the man will be pulling you over to the side of the road with a core drop.

> I understand the reason to say that is because that point still points
> to the same space and the contents of it is not disturbed. (Same to
> the other points point to the same space.)  But I work on a Sun3
> machine under unix system, there are more than one process running
> at the same time. So will other processes take that space and change
> its contents? The answer must be yes to my understanding. Please
> confirm me.

Different processes execute in thier own address space.  The free(3) library
function does not return any space to the OS and therefore it will not be
available to other processes.  If it did return the space to the OS, the 
pointers would now be pointing out of your memory space and you would get
some form of a core drop.

>  Even if no (mc)alloc()'s are called after free() in a
> process, how about calls to other functions with local varibles?

Local variables are placed on the "stack" which is a different portion
of your address space and is not normally adjacent to your allocated data
region.  A sample picture of a c program layout would be something like the 
following:

	+-----------------------------------+
	|				    |
	|  text        			    |
	|				    |
	+-----------------------------------+
	|				    |
	|  Initialized data		    |
	|				    |
	+-----------------------------------+
	|				    |
	|  Uninitialized data		    |
	|				    |
	+-----------------------------------+
	|				    |
	|  stack region (grows down)        |
	|				    |
	:				    :
	:				    :
	:				    :
	:				    :
	:				    :
	|				    |
	|  allocated data region (grows up) |
	|				    |
	+-----------------------------------+

This picture can vary from machine to machine, but the concept is that 
there are two (three if you count shared memory) growable data regions in 
an executing program and never the twain shall meet.



More information about the Comp.lang.c mailing list