#include <stdio.h> int foo1(void) { int p; p = 99; return p; } char *foo2(void) { char buffer[] = "test_123"; return buffer; } int *foo3(void) { int t[3] = {1,2,3}; return t; } int main(void) { int *p; char *s; printf("foo1: %d\n", foo1()); printf("foo2: %s\n", foo2()); printf("foo3: %d, %d, %d\n", p[0], p[1], p[2]); return 0; }
When I compile this with gcc -ansi -pedantic -W -Wall
the compiler issues warning messages for foo2() and foo3():
warning: function returns address of local variable
I thought it is not allowed to return a local variable, but foo1() works fine and it seems there is a huge difference between returning pointer to a local object and the object itself.
Could anybody shed some light on this issue? Thanks in advance!
Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.
Once the function returns it does not exist anymore and hence you should not return the address of a local variable. In other words the lifetime of a is within the scope( { , } ) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid.
When the execution of the function terminates (returns), the local variables are destroyed. Codelens helps you visualize this because the local variables disappear after the function returns.
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.
The issue here is that when you create the local variable it is allocated on the stack and is therefore unavailable once the function finishes execution (implementation varies here). The preferable way would be to use malloc()
to reserve non-local memory. the danger here is that you have to deallocate (free()
) everything you allocated using malloc()
, and if you forget, you create a memory leak.
For foo1()
, you return a copy of the local variable, not the local variable itself.
For the other functions, you return a copy of a pointer to a local variable. However, that local variable is deallocated when the function finishes, so you end up with nasty issues if you try to reference it afterwards.
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