From: Joe Wright Newsgroups: comp.os.msdos.djgpp Subject: Re: free() question Date: Wed, 08 Jan 1997 16:44:58 -0500 Organization: Alpha Solutions Lines: 53 Message-ID: <32D4155A.51F4@exis.net> References: <199701081113 DOT MAA01144 AT gilberto DOT physik DOT rwth-aachen DOT de> Reply-To: wrightj AT exis DOT net NNTP-Posting-Host: ppp-5-157.exis.net Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Christoph Kukulies wrote: > > > Hi, > > > > Just a small question about free() function > > > > Let's : > > > > char *ptr1,*ptr2; > > > > ptr1=(char*)malloc(sizeof(char)*1024); > > if (ptr1!=NULL) ptr2=ptr1; > > .... > > > > //so my question. May i use > > free(ptr2); > > Yes, you may use ptr2 as well. It's the address that corresponds to > the malloc that's freed, not the pointer. > But beware, in the example given you should only free(ptr1) > or free(ptr2) if ptr1 or ptr2 have been initialized > to some senseful value. > > In the above code portion ptr2 doesn't get initialized and if > the malloc returned a 0 for some reason you would invoke > free() later with a wild pointer. > > > //or i have to use > > free(ptr1) > > > > -- > > Regards, > > Dim Zegebart, > > Moscow Russia. > > > > --Chris Christoph P. U. Kukulies kuku AT gil DOT physik DOT rwth-aachen DOT de Good habits are as hard to break as bad ones. I always check the return from malloc (or fopen) in a conditional like: if ((ptr1 = (char *)malloc(1024)) == NULL) do_not_pass_go(); ptr2 = ptr1; There is little you can do if malloc() fails and there is no use continuing with the program. Make it stop and try to fix it. In any case, if malloc() fails, neither ptr1 nor ptr2 contain valid pointers. And there is nothing to free() anyway. -- Joe Wright mailto:wrightj AT exis DOT net "Everything should be made as simple as possible, but not simpler." --Albert Einstein--