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.
You should only free
something which you malloc
ed (or used another similar function) first. Since nothing was malloc
ed, nothing should be free
d.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With