Hacker News new | ask | show | jobs
by adam-f 4585 days ago
A neat trick (tm) for allocating a linked list: recursively call a function which allocates a node on the stack, hooking them up in the function... call something else and pass the list to it.

at the exit condition (whatever that is), exit the recursion and call something else with your new linked list.

(I used something similar to keep track of scope while recursively evaluating in this toy language I made once.)

3 comments

This is kind of bad to do in a kernel. It is up to you to map the pages of your own stack. Once you have higher level concepts like a process, it's fair for the kernel to look at that state from a privileged position and say "OK, I will allocate more stack pages as it faults, and kill the process if I fail or it goes too far". But for kernel mode code, that last part could lead you to a scary place. IMO it's better to just use a few pages for stack and not go crazy with recursive functions.
Plus if you have your kernel stacks allocated in the same virtual address space, you might not be able to just "grow the stack" since that memory may be in use.

But yes recursion in a kernel is a "bad thing" unless you know the recursive bound.

A friend of mine wrote something up on this technique a while ago: http://spin.atomicobject.com/2012/11/01/hey-c-is-a-functiona...
Isn't this just a simplified version of Cheney on the MTA? (http://home.pipeline.com/~hbaker1/CheneyMTA.html)
The book Modern Compiler Implementation in C has a very functional style, written in 1997
There are editions of the book using ML and Java. Since Andrew Appel is involved with SML/NJ, the ML edition is most likely the original. (The ML one is also quite good.)
OT but I've never seen anyone write semicolons that way in C.
Commas?

Personally, I'm never a fan of punctuation first formatting styles - though I give some exception for dot (.) first method calls in fluent interfaces for C-family languages.

    someInterface
       .thatCan()
       .chain()
       .itsCalls();
Yeah, commas.
I imagine you basically mean that the called function stack-allocates one list node, sets up a "return trampoline" so when a return is executed, the returned value is returned one more level up, then jumps back into the code that called it. The issue I see is that returning gets to be a somewhat more expensive operation due to having to return several levels up.

Am I completely wrong here?