Sharing Memory Between Functions and Ownership

Learn about memory ownership.

We'll cover the following


The ownership of local variables is clear. A function creates a local variable, uses it, and upon finishing its execution, it deallocates the local data.

We say that the function owns the variables or the memory. For example:

void func()
    int x = 3;
    x = x + 5;

    printf("%d\n", x):

The scope of the local variable x is limited to the func function. We can say that func owns the variable x.

However, consider the following example, which involves dynamic memory allocations:

int* func()
    int* x = malloc(sizeof(int));
    if(x == NULL)
        return NULL;

    *x = *x + 5;
    return x;

void func2()
    int* x = func();
    if(x != NULL)
        printf("%d\n", *x);


The func function allocates memory for a variable x. But then a pointer to this memory block is returned for use inside func2, which calls func. Who owns x? Is it the func function or the func2 function? The func function allocates x, but func2 uses and frees x.

To answer this question, let’s consider a more detailed example.

The strdup function

The strdup function creates a dynamically allocated copy of a string. Don’t confuse it with strcopy, which copies the data from a source buffer to a destination buffer, and we have to pass both. The strdup function takes only a source buffer (str) and dynamically allocates the destination buffer, returning a pointer to it (char*).

char * strdup( const char *str );

Below is an example of using strdup. We use it to duplicate the string str, in line 10. Note that str is a read-only string (string literal), while duplicate is a read-write string, as it’s a dynamically allocated copy.

Get hands-on with 1200+ tech skills courses.