Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!virtech!cpcahil From: cpcahil@virtech.UUCP (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: <1011@virtech.UUCP> Date: 14 Aug 89 01:23:46 GMT References: <319@cubmol.BIO.COLUMBIA.EDU> Organization: Virtual Technologies Inc Lines: 47 In article <319@cubmol.BIO.COLUMBIA.EDU>, ping@cubmol.BIO.COLUMBIA.EDU (Shiping Zhang) writes: > > When some space is allocated using calloc() or similar routines > and assigned to more than one point, for example as in following lines, > > int *pt1,*pt2; > > pt1=(int *)calloc(100,sizeof(int); > pt2=pt1; > > then if free() is called using ONE of the points, say pt1, as its > argument, is the space pointed by pt1 really freed? Actually I have > two questions about this problem above. > First, can pt2 still be used as a valid point? In other words, > is pt2 still pointing to the location it is assigned to? If you call free(pt1), both pt1 and pt2 will still point to the same address, but this address is no longer "assigned". A future memory allocation may use part of, or all of the same data space. There is no guarranty that the next allocation will use it or won't use it. > My answer to this question SEEMS yes according to some tests I made. > Second, would the space still pointed to by pt2 be reallocated > by other calls to calloc() or other similar funtions? > According to the document I read about free(), the space pointed > by the argument to free() is made available for further allocation, > though its contents are left unchanged. But it does not say what will > happen to the other points pointed to the same space. > A free() will release the "reservation" on data space that was obtained via any of the memory allocation routines. A pointer into an area that has been freed (be it a pointer to the beginning, middle, or end) may and may not work. Using such a pointer is a very bad practice and will usually bite you in the *ss. You seem to be confused about what a pointer acutally is. The only function of a pointer is to contain the address of a memory position. Once you assign a memory position to a pointer this value will not change unless you change the pointer itself, so the free() will not have any effect on either pointer, but will affect whether the data at the memory position they point to is "reserved" for access through that pointer. This is similar to the problem of returning the address of an automatic variable. The address was valid while the function that contained the variable was executing, but once that function ends, the data area on the stack is freed for use by other routines. You might be able to use the address with no problem (although this is a bug that will almost always catch up with you some time in the future).