473,396 Members | 2,076 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Memory and References

What happens when you return a reference to a local variable?

for example:

#include <iostream>
#include <cstdlib>
using namespace std;

int& testf()
{
int x = 1;
return x;
}

int main(int argc, char *argv[])
{
int &y = testf();
cout << y << endl;
return 0;
}
//--------end sample code

This results in outputting "1", but I don't understand whether that
makes sense intuitively. Wouldn't the local variable 'x' in testf() be
deallocated after the function returns? What, then would 'y' be
referencing? How come the compiler even allows this?

Sep 13 '05 #1
3 1041
<jo***********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
What happens when you return a reference to a local variable?
Undefined behavior.
for example:

#include <iostream>
#include <cstdlib>
using namespace std;

int& testf()
{
int x = 1;
return x;
}
That's undefined behavior because x is an automatic object, whose life ends
at the time testf completes.
int main(int argc, char *argv[])
{
int &y = testf();
cout << y << endl;
return 0;
}
//--------end sample code

This results in outputting "1", but I don't understand whether that
makes sense intuitively.
Undefined behavior sometimes results in meaningful things to happen. You see
1 likely because nobody writes anything else on the memory where x lived a
little while ago. That memory still contains 1, and the invalid access to
that memory treats it as int and displays 1.
Wouldn't the local variable 'x' in testf() be
deallocated after the function returns? What, then would 'y' be
referencing? How come the compiler even allows this?


Your compiler may be asked to warn you in such cases. g++, even without
using any warning options says:

warning: reference to local variable `x' returned

Ali
--
Plug: ACCU's Silicon Valley Chapter meets on second Tuesdays. The meetings
are open to public and free of charge. Please come tonight for a talk on
Ada:

http://accu-usa.org/index.html

Sep 13 '05 #2
I think you just got (un)lucky. Here is my run.

[nan@conjecture test]$ g++ -Wall ref.cpp && ./a.out
ref.cpp: In function `int& testf()':
ref.cpp:7: warning: reference to local variable `x' returned
134513944

In general, the outcome is undefined.

Sep 13 '05 #3
Ali Çehreli wrote:
<jo***********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
What happens when you return a reference to a local variable?


Undefined behavior.
for example:

#include <iostream>
#include <cstdlib>
using namespace std;

int& testf()
{
int x = 1;
return x;
}


That's undefined behavior because x is an automatic object, whose life ends
at the time testf completes.
int main(int argc, char *argv[])
{
int &y = testf();
cout << y << endl;
return 0;
}
//--------end sample code

This results in outputting "1", but I don't understand whether that
makes sense intuitively.


Undefined behavior sometimes results in meaningful things to happen. You see
1 likely because nobody writes anything else on the memory where x lived a
little while ago. That memory still contains 1, and the invalid access to
that memory treats it as int and displays 1.
Wouldn't the local variable 'x' in testf() be
deallocated after the function returns? What, then would 'y' be
referencing? How come the compiler even allows this?


Your compiler may be asked to warn you in such cases. g++, even without
using any warning options says:

warning: reference to local variable `x' returned

Ali
--
Plug: ACCU's Silicon Valley Chapter meets on second Tuesdays. The meetings
are open to public and free of charge. Please come tonight for a talk on
Ada:

http://accu-usa.org/index.html


Great, Thanks!

Sep 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Brad Tilley | last post by:
When memory usage is a concern, is it better to do: from X import Y or import X Also, is there a way to load and unload modules as they are needed. I have some scripts that sleep for...
0
by: Andreas Suurkuusk | last post by:
Hi, I just noticed your post in the "C# memory problem: no end for our problem?" thread. In the post you implied that I do not how the garbage collector works and that I mislead people. Since...
0
by: HeroOfSpielburg | last post by:
hi, I know this is a much-travelled subject, but I was wondering what people's thoughts were on the bare minimum (and conversely the grand scheme) for augmenting standard memory references to...
25
by: Zeng | last post by:
I finally narrowed down my code to this situation, quite a few (not all) of my CMyClass objects got hold up after each run of this function via the simple webpage that shows NumberEd editbox. My...
8
by: Adrian | last post by:
Hi I have a JS program that runs localy (under IE6 only) on a PC but it has a memory leak (probably the known MS one!) What applications are there that I could use to look at the memory usage of...
18
by: diffuser78 | last post by:
I have a python code which is running on a huge data set. After starting the program the computer becomes unstable and gets very diffucult to even open konsole to kill that process. What I am...
13
by: sonjaa | last post by:
Hi I'm new to programming in python and I hope that this is the problem. I've created a cellular automata program in python with the numpy array extensions. After each cycle/iteration the...
5
by: Santiago Romero | last post by:
Is there a way to check the REAL size in memory of a python object? Something like or or something like that ...
2
by: Jack Jackson | last post by:
On Wed, 11 Jun 2008 07:32:30 +0200, "Fred" <foleide@free.fr.invalid> wrote: If the control will soon be eligible for garbage collection, then no. If the control won't be eligible for garbage...
2
by: Tom Shelton | last post by:
On 2008-04-15, DR <softwareengineer98037@yahoo.comwrote: Where are you seeing that? In the task manager? If so, then you are looking in the wrong place. Let me tell you a little something...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.