Question: Say I'm implementing a generic stack structure for a library. Here's a sample chunk:

```
typedef struct stack
{
    void* key;
    struct stack* next;
    void*(*alloc_fn)(void*);
} stack;

static stack* make_stack_node(void* val, stack* next,
                              void*(*f)(void*))
{
    stack* node = malloc(sizeof(stack));
    if (!node) {
        return NULL;
    }
    node->key = f(val);
    node->next = next;
    node->alloc_fn = f;
    return node;
}

```

The stack stores a function pointer which points to a function, specified by the user and used for allocating. `make_stack_node` takes just that function. Example for a stack of `int`s:

```
static void* alloc_stack(void* val)
{
    int* p = malloc(sizeof(int));
    *p = *(int*)val;
    return p;
}

```

My question is: when I `malloc` memory for the `node` in `make_stack_node` and afterwards when I allocate memory for the `int` in `alloc_stack`, am I allocating too much? Is there a memory leak when I make `node->key = f(val);`? 

I believe so, because I think memory for `node->key` has already been allocated during the allocation of `node`, so when I allocate memory for the `int*` and I assign that chunk to `node->key`, doesn't that leak the previous thing `node->key` was pointing to?

Answer: 
You are not allocating memory for `int*`, you're allocating memory for `int`. And no, there is no memory leak provided you release the memory.

When you allocate memory for the `stack` the `key` doesn't point anywhere in specific. It's an undefined pointer that you must not dereference. You are required to allocate memory for it to point to just the way you are doing (or set it to point to an already allocated memory).
> 
> *Is there a memory leak when I make `node->key = f(val);`?*
> 
> 
> 

When you assign to `node->key` in `make_stack_node`, `node->key` doesn't point to anything yet, so no memory is leaked.

If you were to assign to `node->key` later in your program, you would need to call `free(node->key)` first to avoid leaking the memory allocated by `alloc_stack` during the call to `make_stack_node`.