I want to make a function that returns a pointer to a locally-defined variable. For the sake of argument, I'll call the function struct awesome *makeCoolStruct()
(I don't want to declare the variable in the outer scope which should have the call struct awesome coolness = makeCoolStruct();
because the function will be called in more than one place).
I understand why the compiler errors out when I try doing that - the local variable will be 'destroyed' as soon as the program exits that scope, so the pointer will basically be invalid.
I looked up how to return a pointer to a local variable in a function, and while I get why malloc
would work, that defeats the purpose of trying to do it this way, because malloc
, as far as I understand, keeps the variable for as long as the program runs - or until free
is called. However, that means that I'll have to have free
called at the end of anything that calls my function. At that point, I'd be better off declaring the variable in every calling scope and then passing a pointer to it like makeCoolStruct(&existingVariable);
.
If, however, there's a way to declare "keep this variable for 1 position higher in the stack" (which would obviously produce a compilation error in the global scope since there are no higher positions in the stack), then I could return a pointer and it'll exist just fine for as long as I need it to, wherever I decide to call struct awesome x = makeCoolStruct();
(I'm aware of the mutability issues - I'm not looking for mutability). I could truly return anything I want in a function from that point on, not just stuff that was passed in.
I haven't really tried anything because I don't know of anything that would work.
I expect to be able to return a pointer to a local variable after doing whatever keeps the variable for one scope higher, without having to do any preparations for the function call when I call it (creating a variable for it to use for the output instead of just assigning the output to something.