'If I 'Malloc' within a function, can I free that memory in the main function?

typedef struct animal
{
    char* name;
    struct animal* next;
}
animal;

animal *create_list(char* name);

int main(void)
{
    animal *head = create_list("giraffe");

    printf("%s\n", head->name);

    free(head);
}

// Initialise list
animal *create_list(char* name)
{
    animal *start = malloc(sizeof(animal));

    if (start == NULL)
    {
        printf("No memory avail.");
        return NULL;
    }

    start->name = name;
    start->next = NULL;

    return start;
}

I think that when the function 'create_list' returns, the pointer 'start' is destroyed. The pointer 'head' in the main function now points to that location in memory, and freeing 'head' at the end should free that memory.

Is this correct? Thanks!



Solution 1:[1]

Within the function the pointer start itself has automatic storage duration and will be destroyed after exiting the function.

The value of the pointer is returned from the function and is the address of the dynamically allocated memory that was not freed in the function.

So using the returned value assigned to the pointer head the dynamically allocated memory can be freed in main.

Pay attention to that this call

free(head);

does not free the pointer. It frees the dynamically allocated memory pointed to by the pointer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vlad from Moscow