Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will C free memory of struct

I've got a question to C structs and datatypes. I have a struct called test:

struct test
{
    char* c;
    char* c2;
};

And I am returning this struct from a function:

struct test a()
{
    struct test t = { "yeah!", "string" };
    return t;
}

My question is whether the memory for the struct is freed automatically or if I have to do this manually via free().

[update from comment:]

The function a is in a DLL and I want to use the struct in the main program.

like image 941
Luca Schimweg Avatar asked May 16 '16 14:05

Luca Schimweg


2 Answers

You should only free something which you malloced (or used another similar function) first. Since nothing was malloced, nothing should be freed.

like image 182
SergeyA Avatar answered Oct 19 '22 18:10

SergeyA


TL/DR Version: You do not need to manually free anything; you can treat this struct instance the way you would treat any scalar variable.

Slightly Longer Version: The struct instance t has automatic storage duration, meaning its lifetime extends over the lifetime of the a function; once a exits, any memory allocated for t is released. A copy of the contents of t is returned to the caller.

As for those contents...

c and c2 are pointing to string literals; string literals are allocated such that their lifetime extends over the entire program's execution. So the pointer values in c and c2 will be valid after t is returned from a; indeed, those pointer values will be valid over the lifetime of the program.

You should only have to call free on something that was allocated via malloc, calloc, or realloc.

like image 21
John Bode Avatar answered Oct 19 '22 17:10

John Bode