TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: Frank Adam
from: Lewin Edwards
date: 1996-05-24 21:31:40
subject: free()

FA> Could someone tell or show me how to free dynamically allocated 
FA> memory in one function from another function or main ?
FA> main()
FA> {
     char *local_copy_of_s=foo();
     /* process local_copy_of_s */
     free(s);
FA> }
FA> char* foo()
FA> {
FA>  char *s = malloc(80);
FA> }

But probably a better way is :

main() {
   char *s=malloc(256);  /* or whatever */
   foo(s);
   fiddle_with(s);
   free(s);
   s=NULL;  /* so later on we can use if (s!=NULL) to determine if this
   pointer is still pointing to an allocated block or not */
}

int foo(char *s) {
   /* process s */
   return 0; /* or result code */
}

This way you are keeping data which are within the scope of main(),
actually WITHIN main(). foo doesn't care about this s in particular, it
just processes strings. main knows and cares about this s in particular,
but doesn't know or care about what foo does and shouldn't need to. The way
I've rewritten it involves less assumptions about the contents of foo()
from main's part.

Also I don't like allocating memory inside functions where it isn't
necessary. It makes keeping track of allocation and deallocation more
difficult. It can be necessary, eg linked list primitives, but in this case
it is definitely inelegant (imo).

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. 

DON'T DO IT. It will probably work in DOS most of the time unless your
program contains an interrupt handler or something else which might fiddle
with the heap. But it's very dangerous practise, just about totally
non-portable, and an extremely bad habit.

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 

DON'T DO IT.
DON'T DO IT.
DON'T DO IT.

In protected mode, you free a chunk of memory, the memory manager is quite
within its rights to use the selector for something else. Bingo ! GPF as
soon as you try to dereference the pointer.

DON'T DO IT.
DON'T DO IT.
DON'T DO IT.

-- Lewin A.R.W. Edwards [Team OS/2]  Tel 0419320415 * 0412809805 * 0414927056
@EOT:

--- MsgedSQ/2 3.35
* Origin: ZWSBBS +61-3-98276881(14k4)/+61-3-98276277(28k8) (3:634/396)
SEEN-BY: 50/99 620/243 623/630 632/348 360 998 633/371 634/388 396 398
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: 634/396 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™.