Message-Id: Comments: Authenticated sender is From: "Salvador Eduardo Tropea (SET)" Organization: INTI To: lubaldo AT adinet DOT com DOT uy Date: Thu, 6 Aug 1998 14:26:17 +0000 MIME-Version: 1.0 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Subject: Re: How do I free the allocated memory? CC: djgpp AT delorie DOT com In-reply-to: <3.0.1.32.19980806004203.007a2750@adinet.com.uy> References: Precedence: bulk lubaldo AT adinet DOT com DOT uy wrote: > At 10:32 AM 05/08/1998 +0000, you wrote: > >gah AT jet DOT es (Grzegorz Adam Hankiewicz) wrote: > > > >> I wanted to create a function which accepts a char string, manipulates > >> it at returns a new one. I thought about this: > >> > >[snipped] > >> Ok, so I learned that after mallocing some memory I always have to > >> free it. But know, since I am returning the pointer, I cannot free the > >> memory before returning the pointer, and I cannot free the memory > >> after (the compiler will never reach that line). > >> > >> So, how do I free that allocated mem? > > > >1) Don't allocate the memory before checking new_str. > >2) Don't allocate a fixed ammount, calculate it. > >3) Use it > > new_s=modify_string(old); > > if (new_s) > > { > > .... use it .... > > free(new_s); > > } > > > >Use something like that: > > > >> char *modify_string ( char *old_str) > >> { > >> char *new_str; > >> > >> if (new_str == NULL) return NULL; > Are you sure this is ok SET? You are comparing against a pointer that has > garbage... whats the point? It can fail... Yes sorry it must be: > >> if (old_str == NULL) return NULL; To avoid a crash if old_str was NULL. > >> new_str = malloc (strlen(old_str)+1+ len added by the formatting > string); // That's enough for me. > >> > >> sprintf( new_str, "Blah,blah %s", old_str); > >> > >> return new_str; > >> } > > set ------------------------------------ 0 -------------------------------- Visit my home page: http://set-soft.home.ml.org/ or http://www.geocities.com/SiliconValley/Vista/6552/ Salvador Eduardo Tropea (SET). (Electronics Engineer) Alternative e-mail: set-soft AT usa DOT net set AT computer DOT org ICQ: 2951574 Address: Curapaligue 2124, Caseros, 3 de Febrero Buenos Aires, (1678), ARGENTINA TE: +(541) 759 0013