C Programming: malloc() inside another function

How should I pass a pointer to a
function and allocate memory for the
passed pointer from inside the called
function?

Ask yourself this: if you had to write a function that had to return an int, how would you do it?

You’d either return it directly:

int foo(void)
{
    return 42;
}

or return it through an output parameter by adding a level of indirection (i.e., using an int* instead of int):

void foo(int* out)
{
    assert(out != NULL);
    *out = 42;
}

So when you’re returning a pointer type (T*), it’s the same thing: you either return the pointer type directly:

T* foo(void)
{
    T* p = malloc(...);
    return p;
}

or you add one level of indirection:

void foo(T** out)
{
    assert(out != NULL);
    *out = malloc(...);
}

Leave a Comment