Referencing a variable allocated in heap

I recently picked up C but am a little confused about how we reference something allocated in the heap.

For example, assume we did something as follows:

void test(){

    int *a;
    a = (int*)(malloc(sizeof(int)*4));
    a[0] = 1;
    a[1] = 2;
    a[2] = 0;
    a[3] = 0;
}

Now, let's say I am in main, obviously, I cannot do something like a[0]=... outside the function as there is no reference to a, but it is allocated in the heap, so how would I make a reference to it? I am guessing I'd have to return an int* or store the address to a outside the function.


Solution 1:

I am guessing I'd have to return an int* or store the address to a outside the function.

Yes, that is exactly how it works.

malloc allocates a block of memory for you and returns a pointer to the first byte of that memory block.

You must make sure to always keep a pointer to the memory block until you call free on it.

This can be done by either returning a pointer to it from the function:

int* test(void){
    int *a;
    a = (int*)(malloc(sizeof(int)*4));
    //... (Also check here that malloc didn't return NULL.)
    return a;
}

or by storing it somewhere else, e.g. an out-parameter passed to the function or a global variable.

If you leave the function without storing or returning a copy of the pointer anywhere, then you loose the last pointer to the memory block (a) and there will be no way to ever reach it again.

This latter situation is known as a memory leak.

store the address to a

It should be the address held by a, not the address of a. a's value is the address of the allocated memory's first byte. The address of a is the address of the pointer variable itself.