I have a struct and a function that returns an instance of Foo defined as follows:
struct Foo
{
int a;
int* b;
};
struct Foo makeFoo(int a, int bSize)
{
struct Foo foo;
foo.a = a;
foo.b = malloc(sizeof(int) * bSize);
for (int i = 0; i < bSize; ++i)
foo.b[i] = i;
return foo;
}
Initially, I thought foo
is a local variable and it'll be gone whenmakeFoo
returns, but from this question Is it safe to return a struct in C or C++?, I know that it's safe to do so.
Now my question is when will memory for foo
be collected? Do I have to free
its b
member first?
Let's say I use makeFoo
like this:
void barFunc()
{
struct Foo foo = makeFoo(3, 10);
printf("Foo.a = %d;\nFoo.b = [", foo.a);
for (int i = 0; i < 10; ++i)
printf("%d, ", foo.b[i]);
printf("\n");
}
void main(int argc, char* argv)
{
barFunc();
}
When barFunc
returns and I'm back in main
, is memory for foo
collected yet? Or do I have to call free(foo.b)
at the end of barFunc
?