1

My question is about returning a value from a function call in c. I've read many questions and answers on this topic such as: Returning a local variable confusion in C

I also understand that returning a pointer to a local variable is a problem since the local variable has no limited lifetime after the return. In my case below I am returning a pointer value not a pointer to a local variable. This should be ok yes? (i.e. returning &x would be bad)

int *foo(int a) {
    int *x;  //local scope local lifetime
    ...
    x = &something_non-local;
    ...
    return x;  //return value of pointer
}
int main(void) {
    int *bar;
    bar = foo(10);
}
user1160866
  • 157
  • 2
  • 10

1 Answers1

1

You can look at it this way. A variable represents a place in memory. Lifetime of a variable is defined by validity of this place in memory. The place in memory keeps a value. Any copy operation just copies values from one place in memory to another.

Every such memory place has an address. A pointer to a variable is just another variable which value is an address of another variable. A copy of a pointer is just a copy of an address from one place to another.

If a variable is declared in the global scope, than its memory will be valid till the exit of the program. If the variable is declared non-statically in a procedure, then its memory is valid till the end of this procedure. Technically it is probably allocated on stack which gets unallocated when the procedure returns, making this memory not valid.

In your case if pointer x points to a variable from a global scope, the variable itself is valid until the exit from the procedure. However, the return statement copies the value from the x into a different location just before the latter becomes invalid. As a result the value of x will end up in bar. This value is the address of a static variable which is still valid.

There would be a different story if you try to return the address of x, i.e. &x. This would be an address of memory which existed inside of the procedure. After return it will point to an invalid memory location.

So, if your something_non-local points to such a thing, than you are in trouble. It should point to something static or something in heap.

BTW, malloc allocates a memory in heap which is valid till you use free.

Serge
  • 11,616
  • 3
  • 18
  • 28
  • Thanks for the very thoughtful answer. It is as I thought but I wasn’t confident. My example is contrived. The real code is quite a bit more complicated. I’m returning a pointer that I copy from a structure that gets freed in this subroutine. Basically saving the value before the variable that holds it is gone. The location the pointer references is on the heap. – user1160866 Apr 18 '19 at 01:57