www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/06/09:04:41

From: lubaldo AT adinet DOT com DOT uy
Message-Id: <3.0.1.32.19980806004203.007a2750@adinet.com.uy>
Date: Thu, 06 Aug 1998 00:42:03 -0300
To: "Salvador Eduardo Tropea (SET)" <salvador AT inti DOT gov DOT ar>, djgpp AT delorie DOT com
Subject: Re: How do I free the allocated memory?
In-Reply-To: <m0z43Vz-000S4XC@inti.gov.ar>
References: <35c78e73 DOT 7896408 AT news DOT jet DOT es>
Mime-Version: 1.0

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...

>> 	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;
>> }
>
	Goodbye.


Ivan Baldo:
lubaldo AT adinet DOT com DOT uy - http://members.xoom.com/baldo - ICQ 10215364
Phone: (598) (2) 613 3223.
Caldas 1781, Malvin, Montevideo, Uruguay, South America.

(If you have problems with the previous addresses, try this ones:
ibaldo AT usa DOT net, http://baldo.home.ml.org).

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019