TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Roger Scudder
from: Bo Simonsen
date: 2003-10-17 17:30:30
subject: Memory matters

> Indeed, just a big work to free a structure with 
 > mutch allocated memory, is 
 > there a easy way for free'ing such a thing?

 RS> Freeing a structure should be nothing more than one line...

 RS> free(PointerToMyStructure);

Well what then I've

PointerToMyStructure = (Structure*) malloc(sizeof(Structure));
PointerToMyStructure->Var1 = (char*) malloc(strlen(some_other_string)+1);

Then I need to free Var1 and the whole structure.

 RS> Since you say it will be "so much work"  I am thinking 
 RS> that you may be doing something very complicated 
 RS> (perhapse messy).  Maybe you should be rethinking how 
 RS> you allocate the memory in the first place.

I think of what I wrote below.

 >  JB> one handy way to free global allocations is to 
 >  JB> put all the frees in 
 >  JB> an exitfunction and use atexit() to register it.

 > atexit is like a class destructer?

 RS>  No, it calls clean up functions that you register.  
 RS> It's in the standard library.

Hmm, Okay.. Oh there is a man-page for it :-)

 >  JB> another is not to allocate them but instead have them as ordinary 
 >  JB> global variables

 > ?

 RS> This is very basic stuff.  You should never have made 
 RS> it to malloc without first  understanding variable 
 RS> scope and lifetime.

I bet I understand, I did just have problems about understanding the sentence.

 RS> Oh well, I guess we all learn in our own way.  :-)

 RS> Read in your C book about external variables, static 
 RS> external and static internal variables, and scope rules.

I know!

But if I've alot of elements, I need a linkedlist anyhow, and then global
vars, would not effort me.

To free them I still need:

for(tmpStruct=firstStruct; tmpStruct; tmpStruct=tmpStruct->next)
{
   free(tmpStruct);      
}

Hmmm...

Bo



--- Maximus/UNIX 3.03b
* Origin: The Night Express (2:236/100)
SEEN-BY: 633/267 270
@PATH: 236/100 237/9 20/11 106/1 2000 633/267

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