[ale] OT: C not C++ Question

Joseph A Knapka jknapka at earthlink.net
Tue Jan 7 13:31:50 EST 2003


Danny Cox wrote:
> Chris,
> 
> On Sun, 2002-12-29 at 22:40, cfowler wrote:
> 
>>>	You might look into Henry Spencer's alloca() implementation that uses
>>>malloc.  The gcc alloca() allocs mem from the stack, which is reclaimed
>>>automatically when the function returns from the function that uses it. 
>>>Henry's alloca() uses malloc, but keeps the blocks in a linked list. 
>>>Calling alloca(0) in the "top loop" of your program performs garbage
>>>collection.
>>>
>>>
>>
>>Would it protect the programmer in this case:
>>
>>String *tmp = String_new("Hello World!\r\r");
>>tmp = String_new("Hello Again!\r\n");
>>
>>Since tmp got a new pointer the original pointer is forever
>>lost.  In Java that memory will just be reaped by GC but in C
>>it is lost until exit() is called :)
> 
> 
> 	Yep.  Okay, the way it works is by a clever observation: in C, the
> stack either grows up or down (with some exceptions; see below).  There
> is a compile time method of telling it the direction the stack grows, or
> it can determine the direction at run time, the first time it's called.
> 
> 	Now, given that, the alloca routine stores two items at the top of the
> block of mem requested: an address from the stack, and a pointer to the
> next block.  Each time alloca is called, the linked list is scanned,
> looking for addresses "deeper" than itself.  Those that are found are
> freed.

This isn't much like real GC, though.

Chris, I think, will have to give up trying to make C act just
like Java in terms of memory management. You either have to use
a full-fledged GC system, with all that entails, or else resign
yourself to matching up all the allocs and frees. Yes, you can
make that easier for yourself by adopting some handy
programming idioms, but the only way code like:

do_something_to(anObjectAllocatedHere_new());

is going to be correct is if you have a full-fledged garbage
collector behind it. The problem is knowing when objects are
referenced, not knowing when the function that creates them
exits.

Cheers, and Happy Ought Three,

-- Joe

_______________________________________________
Ale mailing list
Ale at ale.org
http://www.ale.org/mailman/listinfo/ale






More information about the Ale mailing list