# When is a function exited from?

Page 1 of 1

## 14 Replies - 711 Views - Last Post: 09 April 2011 - 11:09 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=226804&amp;s=b2b24d36ff0425210c7f6e5022b14a8c&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

# When is a function exited from?

Posted 09 April 2011 - 07:22 AM

Suppose I have this code:

```
int * func()
{
int a=10;
int* p=&a;
return p;

}

int main()
{
int* q=func();

}

```

does q point to a=10 before a is destroyed?

Or better said, what is the order of execution?
This is how I taught:

1. func returns p;
2. q gets the adress of p; (q points now to a=10)
3. a is destroyed (q points now to a garbage value)

or 1,3,2 ?

Which is the correct order?

This post has been edited by livium: 09 April 2011 - 07:57 AM

Is This A Good Question/Topic? 0

## Replies To: When is a function exited from?

### #2 vividexstance

• D.I.C Lover

Reputation: 763
• Posts: 2,679
• Joined: 31-December 10

## Re: When is a function exited from?

Posted 09 April 2011 - 07:52 AM

You don't set p properly in the function, it would be int* p = &a; And to answer your question, it would be 1, 3, 2. You're never supposed to return a local pointer/reference from a function because it is destroyed when the function goes out of scope.

### #3 chinchang

• Indie Game Developer

Reputation: 192
• Posts: 725
• Joined: 22-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 07:53 AM

What is this line supposed to do:

```int* p=a;

```

### #4 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 08:00 AM

vividexstance, on 09 April 2011 - 08:52 AM, said:

You don't set p properly in the function, it would be int* p = &a; And to answer your question, it would be 1, 3, 2. You're never supposed to return a local pointer/reference from a function because it is destroyed when the function goes out of scope.

int* p=&a of course. Sorry about that.
So, first the function ends and then q gets what it returned.
Thank you!

### #5 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 08:19 AM

Can somebody tell me why this code returns 10 and not a undefined value?

```
int& func()
{
int a=10;
return a;
}

int main()
{

int &b=func();
cout<<b;

}

```

because a is returned by reference and then it is destroyed in func, b should not in any case be 10.

### #6 vividexstance

• D.I.C Lover

Reputation: 763
• Posts: 2,679
• Joined: 31-December 10

## Re: When is a function exited from?

Posted 09 April 2011 - 08:28 AM

When you return from that function, a "temporary" variable is created that is an integer in this case and it holds the value '10'. If you return by value from a function, everything is fine. It's when you return a pointer or reference where you have to be careful. If the pointer/reference is to a local variable in a function and you use it as a return value, then when the function exits, that value returned is garbage. Also, most modern compilers will warn you if return a local pointer/reference from a function.

### #7 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 08:33 AM

Vividexstance, please look carefully at my code and u will see i return a reference of a local temporary variable in that function. Altough it should return a garbage value it returns me 10.
Is it the compiler 'fault' ? I use VS2010.

This post has been edited by livium: 09 April 2011 - 08:35 AM

### #8 Oler1s

• D.I.C Lover

Reputation: 1396
• Posts: 3,884
• Joined: 04-June 09

## Re: When is a function exited from?

Posted 09 April 2011 - 08:43 AM

A quick lesson on undefined behavior. It is undefined. Not, "crash", or "incorrect result". Could those happen? Sure. Could something else happen? Sure. We have no idea.

But it certainly isn't something you want to do.

> does q point to a=10

q points to an address that is no longer valid. So while that assignment is correct, dereferencing q is undefined.

> Or better said, what is the order of execution?

a's lifetime ends at end of function scope. &a is not valid immediately after function return.

> Can somebody tell me why this code returns 10 and not a undefined value?

What do you mean by that? You think the result of that is "NAN" or "UNDEFINED" or something? No, that's not what we mean by undefined behavior. What we mean is literally you have no idea what will happen. In your case, you still happened to get the desired value. But a different value, or a segfault, or your computer going up in flames would all be valid responses.

Your problem is you take undefined behavior, then wonder why it doesn't correspond to certain defined behaviors...

### #9 vividexstance

• D.I.C Lover

Reputation: 763
• Posts: 2,679
• Joined: 31-December 10

## Re: When is a function exited from?

Posted 09 April 2011 - 08:51 AM

I'm not 100% sure, but the reason you're getting the correct result has to do with what Oler1s said. You can't just create a reference, a reference needs to reference something, so in your function you create a regular integer, and your function returns a reference to an integer. So like I said before, what's most likely happening, is that a temporary is created that holds the number '10', and you get a return value of a reference to that temporary variable that still holds '10'. Don't count on this always working though. Try to stick with code that is standard conforming and portable.

When I compiled and ran your code on linux using gcc, I got the same results, but I also got this as a compiler warning: "refTest.cpp: In function ‘int& func()’:
refTest.cpp:5: warning: reference to local variable ‘a’ returned"

### #10 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 09:22 AM

[quote name='vividexstance' date='09 April 2011 - 09:51 AM' timestamp='1302364296' post='1305952']

Vividexstance, what you're saying is that the compiler understood that i'm about to make a mistake, and created a temporary variable which was returned by the function as a reference. This is what I understand.

Then, regarding Oler1s reply, what I understood from that is that this practice of mine is wrong because altough the program returns 10 it could also return any other value or a garbage value.
So this is what I understand from undefined behaviour: something which results from something which is logically incorrect or mistakenly taught.
So in this case of mine: the code returned 10, but this value of 10 is something which resulted from an incorrect implementation, and I should not be glad that the code returned 10 because it could also returned me something else, but I was saved by the compiler.

So to conclude: Don't use code which is logically wrong even if you get the desired result.

This post has been edited by livium: 09 April 2011 - 09:27 AM

### #11 vividexstance

• D.I.C Lover

Reputation: 763
• Posts: 2,679
• Joined: 31-December 10

## Re: When is a function exited from?

Posted 09 April 2011 - 09:36 AM

Just to clear one thing up, yes the compiler did know that you were making a mistake(but not all compilers do this), also the temporary variable that is created when you return from the function isn't because you made a mistake. It's something the compiler does for you most of the time, you just don't see it going on. Once you get into classes, you can see this happening if you make a class that outputs when it is created/copied/destroyed. Here's a link for a good book that might help you out: Thinking in C++.

### #12 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 09:46 AM

Thank you.

### #13 Bench

• D.I.C Lover

Reputation: 859
• Posts: 2,343
• Joined: 20-August 07

## Re: When is a function exited from?

Posted 09 April 2011 - 09:49 AM

The problem with undefined behaviour, as already mentioned, is that anything can happen. The word 'anything' is an umbrella term which includes your program appearing to work exactly as you might expect as if nothing is wrong.

Having your program "appear to work" off the back of undefined behaviour is undoubtedly the absolute worst thing which can possibly happen - because it means that a bug in your code is going un-noticed, but you can bet any kind of wager that it'll fall over eventually; when it does, chances are you'll have a far more difficult time figuring out what went wrong. (Although compiling with maximum warning level enabled and using static code analysis tools can help protect you. In this instance, I would expect a compiler with all warnings enabled to let you know that its bad)

### #14 livium

Reputation: 0
• Posts: 543
• Joined: 21-December 08

## Re: When is a function exited from?

Posted 09 April 2011 - 10:07 AM

Thank you Bench. I'm glad I understood what undefined behaviour is.

### #15 Nasm

Reputation: 27
• Posts: 47
• Joined: 10-June 10

## Re: When is a function exited from?

Posted 09 April 2011 - 11:09 AM

The reason your code work is be course you never do anything after the function call that could overwrite the memory location.
When you call a function in C the compiler will reserve memory on the stack for any local variables. When the function is finished the stack pointer will be reset allowing the memory location to be overwritten the next time memory is reserved. If you would call another function with a local variable the memory would be overwritten.

If you call this function directly after, your original pointer would now most likely dereference to 5 instead of 10.
```void func2(){
int v = 5;
}
```

Lets take a look on how gcc would translate your function without any optimization:
```func:
pushl	%ebp           # save the value of ebp on the stack
movl	%esp, %ebp     # copy the value of ebp into esp
subl	\$16, %esp      # subtract 16 from the stack pointer (reserve 16 bytes of memory on the stack)
movl	\$10, -4(%ebp)  # copy 10 into the memory location at ebp-4 (this is equal to your a = 10 instruction
leal	-4(%ebp), %eax # load the address ebp-4 into the eax register
movl	%eax, -8(%ebp) # copy eax into the memory location at ebp-8
movl	-8(%ebp), %eax # copy the value at ebp-8 into the eax register (this is the return value)
leave                  #reset the stack and base pointers to their old values (this is equal to movl %ebp, %esp pop %ebp)
ret
```

So what happens when a function is called is, somewhat simplified, that a function gets it's own memory location after the top of the stack and when the function exits the the base pointer (which points to the base of the stack) and the stack pointer (which point to the top of the stack) is reset to their old values and the memory reserved by the function may then be overwritten by subsequent memory allocations.