0

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

When Automatic Memory Deallocated ?

void fun3(int a){
    a = 5;
}

Does 'a' deallocated when the function end ?

Yes !

So What is the reason for this output ? http://ideone.com/2ZJ57

Community
  • 1
  • 1
faressoft
  • 19,053
  • 44
  • 104
  • 146

3 Answers3

2

Technically, the memory where a was stored is available for us by other contexts, so to answer your question, yes.

This depends on some factors though. There might not even be memory to speak of. In your particular example, the optimizer might just cut everything out. Even if you do something like cout << a, a 5 might be inlined which doesn't reside in memory.

Note that if you pass by reference, the lifetime is that of the original variable.

Also, just because it's deallocated that doesn't mean the memory is automatically cleaned afterwards. The value might still reside there until that memory is reused.

Your example exibits undefined behavior:

void fun3(int *&p, int a){
        p = &a;
}

a is a local variable, and you take its address and assign it to p, which you then use outside the function. Anything can happen.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Yes a is deallocated when the scope of the function ends.

So What is the reason for this output ?
Accessing the contents of an automatic variable through an pointer to the memory location beyond the scope in which the variable exists is an Undefined Behavior as per the standard.

Your program does exactly that, so it has an Undefined Behavior(UB). With UB your program can show any behavior valid or invalidRef 1.

Ref 1C++03 section 1.3.24:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

Yes, the storage allocated for a gets deallocated when the function exits.

NPE
  • 486,780
  • 108
  • 951
  • 1,012