delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/06/09:07:32

From: lubaldo AT adinet DOT com DOT uy
Message-Id: <3.0.1.32.19980806004559.007a2930@adinet.com.uy>
Date: Thu, 06 Aug 1998 00:45:59 -0300
To: gah AT jet DOT es (Grzegorz Adam Hankiewicz), djgpp AT delorie DOT com
Subject: Re: How do I free the allocated memory?
In-Reply-To: <35c78e73.7896408@news.jet.es>
Mime-Version: 1.0

	Hello friend :-)

At 11:37 AM 05/08/1998 GMT, you wrote:
>I wanted to create a function which accepts a char string, manipulates
>it at returns a new one. I thought about this:
>
>char *modify_string ( char *old_str)
>{
>	char *new_str;
>
>	new_str = malloc (512);  // That's enough for me.
>	if (new_str == NULL) return NULL;
>
>	sprintf( new_str, "Blah,blah %s", old_str);
	Put "free(old_str);" here...

>	return new_str;
>}
>
>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).
	I don't understand why you cant free the memory... you have a pointer
pointing to some chunk of memory, if that memory was allocated with malloc,
I think that there are no problems. After you use old_str you will not use
that pointer anymore so it is time to free it, after that, return the
new_str pointer with the new allocated chunk of memory. But maybe what you
are saing is that the old_str pointer will be used again after the call? If
that is true, then you have to deallocate it whenever you want... it
doesn't have to be in that function...

	Hope I am not missing something and that I am not being silly...

	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