In a C function, its locals’s memory is allocated when the function is called, and deallocated when function is finished. What about for functions that return a value (e.g. int, string), when and where does the return address’s memory is allocated and deallocated, and is it part of the call stack or the callee stack, or something else?
Consider the following example:
int* foo()
{
int _myInt;
return(&_myInt);
}
This example gets me completely confused as of how memory is allocated for the return address that return a pointer. Can someone please explain?
Same for C and Objective-C?
I don’t know about Objective-C but, with standard C, return values are typically stored in registers.
When the function returns a pointer type, it is up to the developer to ensure the memory pointed to remains valid after the call.
Consider the following function:
This function returns a pointer to local memory, which is deallocated when the function returns. Accessing that memory would constitute a bug with undefined behavior.
This also applies to your example, which is not valid. But since an
intcan fit in a register, you can simply doreturn _myInt;and return the value directly.