[ale] OT: C not C++ Question
Danny Cox
danscox at mindspring.com
Mon Dec 30 12:46:03 EST 2002
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. That's also why a call to alloca(0) (not NULL by the way, you're
passing a size, not a pointer) is suggested in main(), or the "highest"
level you can manage. Note: there is some overhead, obviously. If you
ask for 4 bytes (from alloca), it requests 12, uses 8, and hands you a
pointer to the 4 you asked for. This is not normally a problem,
nowadays, but since this is an embedded machine, every byte counts.
Okay, some machines don't handle the stack by moving stack pointers up
or down. I remember the Cray was one that used a linked list of stack
frames, and therefore wouldn't work with this scheme, or rather, this
scheme doesn't work on certain Crays :-(.
So, this alloca works by a happy coincidence, nothing more. Once
again, this is a big, hairy, purple-polka-dotted kludge! It was
originally invented by Henry to allow emacs to work on machines that
didn't implement alloca (okay, their compilers didn't implement
alloca). Surprisingly, it works on most of the machines out there.
Finally, Chris, this will work if you re-implement all the routines
that call malloc to use a similar method to the Henry Spencer alloca
routine. I don't suggest calling it 'alloca', as gcc will swear
vehemently.
--
kernel, n.: A part of an operating system that preserves the
medieval traditions of sorcery and black art.
Danny
_______________________________________________
Ale mailing list
Ale at ale.org
http://www.ale.org/mailman/listinfo/ale
More information about the Ale
mailing list