1

I recently read about scope rules in C. It says that a local or auto variable is available only inside the block of the function in which it is declared. Once outside the function it no longer is visible. Also that its lifetime is only till the end of the final closing braces of the function body.

Now here is the problem. What happens when the address of a local variable is returned from the function to the calling function ?

For example :-

 main()
 {
     int *p=fun();
 }

 int * fun()
 { 
     int  localvar=0;
     return (&localvar);
 }

once the control returns back from the function fun, the variable localvar is no longer alive. So how will main be able to access the contents at this address ?

Mysticial
  • 464,885
  • 45
  • 335
  • 332
qre0ct
  • 5,680
  • 10
  • 50
  • 86
  • Use explicit return types on all functions, including `main`. Thus: `int main(void)`. – Jonathan Leffler Dec 10 '11 at 03:45
  • *head scratch*. Pragmatically, you wouldn't return the address. you'd return the value that was in localvar, in which case, that function declaration is wrong (as it needs to return an `int` not an `int *`). – JayC Dec 10 '11 at 03:50
  • possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Nick Meyer Dec 10 '11 at 03:51
  • See the question I marked this as duplicate of. The phrasing is slightly different, but the code is the same and it has an excellent answer from Eric Lippert. – Nick Meyer Dec 10 '11 at 03:53
  • @user980153 You don't need to copy and paste the same comment on to everyone's answer. – Mysticial Dec 10 '11 at 03:57
  • @Mysticial...ok m sorry , i guess i did not quite figure it out that just commenting once will make it visible to all. I'll keep that in mind henceforth. – qre0ct Dec 10 '11 at 04:16
  • all right everyone .... thanx for the wonderful replies that everyone gave. it really helped clear my concepts a lot. – qre0ct Dec 10 '11 at 04:19
  • and yeah just so that you guys know it...this forum does not really allow voting multiple answers as correct. But you guys should know i really found all the answers in here pretty satisfactory. – qre0ct Dec 10 '11 at 04:21

3 Answers3

3

The address can be returned, but the value stored at the address cannot reliably be read. Indeed, it is not even clear that you can safely assign it, though the chances are that on most machines there wouldn't be a problem with that.

You can often read the address, but the behaviour is undefined (read 'bad: to be avoided at all costs!'). In particular, the address may be used for other variables in other functions, so if you access it after calling other functions, you are definitely unlikely to see the last value stored in the variable by the function that returned the pointer to it.


Why then is a function returning a pointer ever required?

One reason is often 'dynamic memory'. The malloc() family of functions return a pointer to new (non-stack) memory.

Another reason is 'found something at this location in a value passed to me'. Consider strchr() or strstr().

Another reason is 'returning pointer to a static object, either hidden in the function or in the file containing the source for the function'. Consider asctime() et al (and worry about thread-safety).

There are probably a few others, but those are probably the most common.

Note that none of these return a pointer to a local (stack-based) variable.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Yeah that is exactly what i guessed. But then can you please elaborate why then is a function returning a pointer ever required ? I mean what is the use of it, because every time we try to return a reference or an address, of a local variable, from the function to a calling function, the same, above explanation holds true. – – qre0ct Dec 10 '11 at 03:55
0

Referencing that location in memory after the function has returned is dangerous. Of course the location still exists (and it may still contain your value), but you no longer have any claim to that memory region and it will likely be overwritten with new data as the program continues and new local variables are allocated on the stack.

gcc gives me the following warning:

t.c: In function ‘test’:
t.c:3:2: warning: function returns address of local variable [enabled by default]

Consider this test program:

int * test(int p) {
    int loc = p;
    return &loc;
}

int main(void) {
    int *c = test(4);
    test(5);
    printf("%d\n", *c);
    return 0;
}

What do you think this prints?

Wayne
  • 59,728
  • 15
  • 131
  • 126
  • Yeah that is exactly what i guessed. But then can you please elaborate why then is a function returning a pointer ever required ? I mean what is the use of it, because every time we try to return a reference or an address, of a local variable, from the function to a calling function, the same, above explanation holds true. – qre0ct Dec 10 '11 at 03:50
  • @user980153 - The answer to that requires an understanding of the difference between allocating on the stack vs. on the heap. – Wayne Dec 10 '11 at 03:56
0

The variable is gone, but the memory location still exists and might even still contain the value you set. It will however probably get overwritten pretty fast as more functions are called and the memory address gets reused for another function's local variables. You can learn more by reading about the Call Stack, which is where local variables of functions are stored.

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
  • Yeah that is exactly what i guessed. But then can you please elaborate why then is a function returning a pointer ever required ? I mean what is the use of it, because every time we try to return a reference or an address, of a local variable, from the function to a calling function, the same, above explanation holds true. – – qre0ct Dec 10 '11 at 03:56
  • Returning pointers is useful when working with large data structures which you wouldn't want to pass by value all the time as it'd be inefficient. These large structures are usually allocated on the heap using malloc(), and then a pointer to the data is passed into and out of functions. – Paige Ruten Dec 10 '11 at 04:04