Is it possible to create a linked list on the stack in C++?

The difference between heap and stack are mainly (not only, but for the sake of this question mainly) where the memory is allocated and how it is freed. When you want to allocate a node on the heap, you say new Node and the system will provide you with the memory, keeps track of which chunks are used and which ones are free, and provides you with the means to free a chunk once you don't need it any longer.

But you can just as well have a pool of nodes in an array on the stack. (Automatic variables are stack variables.) You can "allocate" from that pool, keep track of which nodes in the array are used and which are free, and mark unused ones as free ones you don't need them any longer. However, since the array's size is fixed at compile-time, this means that you have a maximum length for your list.


I've created a small sample that you may find inspiring. I creates a singly linked list of elements on the stack. Take notice how the list is created in reverse and how recursion is used to 'allocate' the number of itmes you need. Also note how the list is passed to the as the parameter. Hope this helps, good luck.

#include <cstdio>

using namespace std;

struct Node {
    Node* next_;
    int value_;
};

// Creates a linked list of nodes containing raising values.
void intList(Node* prevNode, int restValue) {
    if (restValue) {
       // A node on the stack, which is linked to list created so far.
       Node node;
       node.next_ = prevNode;
       node.value_ = restValue; 
       // Create a next node or print this list if rest runs to zero.
       intList(&node, restValue - 1);
    }
    else {
    // Depest recursion level, whole list is complete.
    for (Node* iter = prevNode; iter; iter = iter->next_)
        printf("item %d\n", iter->value_);
    }
}

int main() {
    intList(NULL, 10);
}

Once a function is called, the stack allocation is fixed for that function.

The only way to get more stack memory allocated would be to call another function. Which could then call another function. Which could then call another function. Or maybe they could all be the same function...

Each function call has it's own fixed-size stack, but the function call graph itself is a variable-sized stack of those stacks.