Search⌘ K

Sharing Memory Between Functions and Ownership

Explore how functions in C share and manage memory ownership, especially with dynamic allocations. Understand when a function owns memory and when it is shared, by examining examples like strdup and strcpy. Learn the importance of freeing allocated memory to prevent leaks by following ownership rules and documentation guidance.

We'll cover the following...

Introduction

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
...