473,406 Members | 2,705 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,406 software developers and data experts.

Returning pointers from functions

Hey guys,
I have a simple question. Suppose we have the following
functions:-

//-----My code starts here

char* f1(char* s)
{
char* temp="Hi";
return temp;
}

char* f2(char *s)
{
char temp[100];
strcpy(temp,"Hi");
strcat(temp,s);
return temp;
}

//-----My code ends here
Now, suppose I have a main function which calls the both. Thing is,
when i compile the prog, the compiler gives me a warning regarding f2
saying that temp is a local variable and i m returning its address.

str1.cpp: In function `char* f2(char*)':
str1.cpp:14: warning: address of local variable `temp' returned

This is fine and expected. But y dont i get the same warning for f1? At
runtime, everything works fine although i guess this is not right as
the memory for the local variables can get overwritten anytime. Pls,
can someone clarify the whole concept. TIA.

Cheers

PS- if this has been discussed already, pls provide the link and my
apologies in dat case.

Nov 14 '05 #1
7 2296
In article <11**********************@g14g2000cwa.googlegroups .com>,
wonderboy <pa********@gmail.com> wrote:
:char* f1(char* s)
:{
: char* temp="Hi";
: return temp;
:}

:when i compile the prog, the compiler gives me a warning regarding f2
:saying that temp is a local variable and i m returning its address.

:This is fine and expected. But y dont i get the same warning for f1?

In f1, you are not returning the -address- of temp, you are returning
the -value- of temp, which happens to be a pointer to a character
array. Compilers often put quoted strings into static storage, as
that saves having to copy in the string each time. It is legal
for compilers to use the -same- location for all instances of
the same quoted string, and it legal for compilers to put quoted
strings into read-only memory.

None the less, -logically- the string could be anywhere
(including on the stack) and so you should not be returning
it's address. Well, you can return it's address, but you
shouldn't -use- that address for anything (other than
as a curiosity) as there is no certainty at all that the
storage will continue to persist, or even that the pointer
will still be usable

[Pointers don't have to have absolute references: it would be legal for
an implimentation to work with a system of "public" and "private"
pointers, where a "public" pointer was an absolute address in virtual
memory but a private pointer was a relative offset from a base register
whose value changed from function to function. It is only legal
to compare pointers with pointers when they are pointers into the
same object.]
--
"I want to make sure [a user] can't get through ... an online
experience without hitting a Microsoft ad"
-- Steve Ballmer [Microsoft Chief Executive]
"I want to make sure [a user] can't get through ... an online
Nov 14 '05 #2
"wonderboy" <pa********@gmail.com> wrote:
char* f1(char* s)
{
char* temp="Hi";
return temp;
}

char* f2(char *s)
{
char temp[100];
strcpy(temp,"Hi");
strcat(temp,s);
return temp;
} str1.cpp: In function `char* f2(char*)':
str1.cpp:14: warning: address of local variable `temp' returned
Be careful! C++ is not C, nor a superset of it. There _are_ things that
function differently in C++ than in C, and I do not know whether this is
one of them.
This is fine and expected. But y dont i get the same warning for f1?


Because a string literal has static duration. This means that it is
created sometime before main() is called, and destroyed just before your
program exits. It is always available while your program runs. In f1 you
aren't returning a pointer to a local variable; you are returning the
value of a local variable, and that value is a pointer to a static
object. It doesn't matter, in this case, that temp will be destroyed
when f1 returns, because the array it points at will not.

Richard
Nov 14 '05 #3
wonderboy wrote:
char* f1(char* s)
{
char* temp="Hi";
return temp;
}
This is okay. You return a copy of the value of temp, which is the address
of the string literal "Hi". The string literal is an array of static
storage duration, which means that it is available throughout the entire
lifetime of the program.
char* f2(char *s)
{
char temp[100];
strcpy(temp,"Hi");
strcat(temp,s);
return temp;
}


This is not okay. You return the address of the first element of temp, which
is an object local to f2. Therefore, references to it become invalid after
exit from the function.
Christian
Nov 14 '05 #4
Walter Roberson wrote:

[ about string literals ]
None the less, -logically- the string could be anywhere
(including on the stack) and so you should not be returning
it's address. Well, you can return it's address, but you
shouldn't -use- that address for anything (other than
as a curiosity) as there is no certainty at all that the
storage will continue to persist, or even that the pointer
will still be usable


This is wrong. The standard mandates that string literals have static
storage duration (6.4.5 ), which means that "[t]he object exists, has a
constant address, and retains its last-stored value throughout the
execution of the entire program" (6.2.4).
Christian
Nov 14 '05 #5
In article <38*************@individual.net>,
Christian Kandeler <ch****************@hob.de_invalid> wrote:
:Walter Roberson wrote:

:[ about string literals ]
:> None the less, -logically- the string could be anywhere
:> (including on the stack) and so you should not be returning
:> it's address.

:This is wrong. The standard mandates that string literals have static
:storage duration

I gotta look into getting the standard on CD. My paper copy is
always somewhere else, and would fall apart even more if I lugged
it around. :(
--
Suppose there was a test you could take that would report whether
you had Free Will or were Pre-Destined. Would you take the test?
Nov 14 '05 #6
Walter Roberson wrote:
Christian Kandeler <ch****************@hob.de_invalid> wrote:
.... snip ...
: This is wrong. The standard mandates that string literals have
: static storage duration

I gotta look into getting the standard on CD. My paper copy is
always somewhere else, and would fall apart even more if I lugged
it around. :(


You can google for N869, or get the just mounted slightly edited
text version (suitable for searching and quoting) at:

<http://cbfalconer.home.att.net/download/n869_txt.bz2>

Please fix your abnormal quote char, which fouls up software meant
to handle usenet quotations.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #7
On 2 Mar 2005 11:14:01 GMT, ro******@ibd.nrc-cnrc.gc.ca (Walter
Roberson) wrote:
In article <38*************@individual.net>,
Christian Kandeler <ch****************@hob.de_invalid> wrote:
:Walter Roberson wrote:

:[ about string literals ]
:> None the less, -logically- the string could be anywhere
:> (including on the stack) and so you should not be returning
:> it's address.

:This is wrong. The standard mandates that string literals have static
:storage duration

I gotta look into getting the standard on CD. My paper copy is
always somewhere else, and would fall apart even more if I lugged
it around. :(


ANSI will sell you a PDF version for $18.00.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #8

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

Similar topics

5
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the...
41
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x...
10
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences...
6
by: Generic Usenet Account | last post by:
Is it okay to return a local datastructure (something of type struct) from a function, as long as it does not have any pointer fields? I think it is a bad idea, but one of my colleagues does not...
9
by: CptDondo | last post by:
I am working on an embedded platform which has a block of battery-backed RAM. I need to store various types of data in this block of memory - for example, bitmapped data for control registers,...
5
by: shyam | last post by:
Hi All I have to write a function which basically takes in a string and returns an unknown number( at compile time) of strings i hav the following syntax in mind char *tokenize(char *) ...
26
by: cdg | last post by:
Could anyone correct any mistakes in this example program. I am just trying to return an array back to "main" to be printed out. And I am not sure how a "pointer to an array" is returned to the...
17
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ...
23
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.