TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: Frank Adam
from: david nugent
date: 1996-05-24 15:12:48
subject: free()

FA> main()
 FA> {
 FA>  foo();
 FA>  }

 FA> char* foo()
 FA> {
 FA>  char *s = malloc(80);
 FA>  }

 FA> If this function is to return s, freeing it before return would not
 FA> be a good idea, is that true ?

That depends. If you needed the block of memory in main(), then you can't
free it until you finish using it. If you don't, then you can free() it any
time after you've used it, whether that be before returning from foo(), or
within main().


 FA> If it is, how would i then get access to s to free it ?

You return it. When you return it, you assign the pointer to the memory to
some other variable in main.

 int main()
 {
  char * mys = foo();
  free(mys);
  return 0;
 }

 FA> It's out of scope, as silly as is i've tried free(s)
 FA> from main, compiler says "what s?" of course.

Aren't you returning it though? Of course 's' is out of scope, but it isn't
"s" that you're freeing, but the block of memory it points to.
You can assign THAT value as you like, including returning it from a
function.

  char * s = malloc(80);
  char * p = s;
  free(p);                  /* Perfectly legal */

 FA> Btw, i have thought about freeing it before returning, and it *seems* to
 FA> work fine in DOS, but i don't know how safe that is.

Perfectly safe. If you don't need it in main, then don't return it!


 FA> I also believe that in a multitask environment, that would be fatal if
 FA> another program got a slice between free() and return, am i thinking
 FA> straight here or not ?

Nope. Multitasking has no relevence at all to use of malloc() and free().
MultiTHREADING environments might be different, but in general the RTL
handles any sort of contention between threads and it is still irrelevant.

--- MaltEd/2 1.0.b6
* Origin: Unique Computing Pty Limited (3:632/348)
SEEN-BY: 50/99 620/243 623/630 632/103 348 360 998 633/371 634/388 396
SEEN-BY: 635/301 502 503 506 544 639/252 711/401 409 410 413 430 808 809 932
SEEN-BY: 711/934 712/515 713/888 714/906 800/1
@PATH: 632/348 635/503 50/99 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.