Luca Schimweg
Luca Schimweg

Reputation: 797

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.

Upvotes: 6

Views: 154

Answers (3)

John Bode
John Bode

Reputation: 123508

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.

Upvotes: 3

Yanis Ismail
Yanis Ismail

Reputation: 73

you do not have to free a non-dynamic allocation. Nevertheless, If you want to use the struct in an other function, you have to pass the address of the struct, and take it as a (struct *), if you don't, you will not be able to use it again.

Upvotes: 0

SergeyA
SergeyA

Reputation: 62583

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

Upvotes: 5

Related Questions