8 Replies - 1465 Views - Last Post: 04 March 2010 - 11:44 PM Rate Topic: -----

#1 gmcdonald73  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 25-February 10

C++ scope of function return values

Posted 04 March 2010 - 08:04 PM

Can anyone tell me at what point the return values from functions are lost if they are not assigned to anything? ie is the const char * passed into displayString guaranteed to valid for this line: displayString(getString().c_str());

using namespace std;

string getString();
void displayString(const char * p);

string getString()
{
	string sVal = "TEST";
	return sVal;
}

void displayString(const char * p)
{
	printf("*** %s ***\n", p);
}

int _tmain()
{
	// This seems to work - is this guaranteed?
	displayString(getString().c_str()); 

	// This doesn't work - the string that is returned by getString() goes out of scope immediatiely after this line
	const char * p2 = getString().c_str();
	displayString(p2); 
}



Is This A Good Question/Topic? 0
  • +

Replies To: C++ scope of function return values

#2 javabie  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 117
  • Joined: 12-February 10

Re: C++ scope of function return values

Posted 04 March 2010 - 08:26 PM

why use char * and all those when c++ already has string???

this c++ code seems to be working with XCode...
you might rename the main to _tmain as your original post had it.


#include <iostream>
using namespace std;

string getString();
void displayString(string p);

string getString()
{
	string sVal = "TEST";
	return sVal;
}

void displayString(string p)
{
	cout <<"***** "<< p << " *****"<<endl;
}

int main()
{
	displayString(getString().c_str()); 
	
	string p2 = getString().c_str();
	displayString(p2); 
	
	return 0;
}



as for the scope of return values,
you need to assign the return value to some variable, otherwise there is no variable pointing/referencing to the value returned by the function.

so for example,
assume that string myString() exists...


      myString(); // will return a string but you need to store it into variable to use it.....


so sumthing like...
  string myStr = myString();
  cout << myStr;
   //you could use it many times...

  cout << "printing it again.." << myStr;
 

Was This Post Helpful? 0
  • +
  • -

#3 gmcdonald73  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 25-February 10

Re: C++ scope of function return values

Posted 04 March 2010 - 08:53 PM

View Postjavabie, on 04 March 2010 - 07:26 PM, said:

why use char * and all those when c++ already has string???

this c++ code seems to be working with XCode...
you might rename the main to _tmain as your original post had it.


#include <iostream>
using namespace std;

string getString();
void displayString(string p);

string getString()
{
	string sVal = "TEST";
	return sVal;
}

void displayString(string p)
{
	cout <<"***** "<< p << " *****"<<endl;
}

int main()
{
	displayString(getString().c_str()); 
	
	string p2 = getString().c_str();
	displayString(p2); 
	
	return 0;
}



as for the scope of return values,
you need to assign the return value to some variable, otherwise there is no variable pointing/referencing to the value returned by the function.

so for example,
assume that string myString() exists...


      myString(); // will return a string but you need to store it into variable to use it.....


so sumthing like...
  string myStr = myString();
  cout << myStr;
   //you could use it many times...

  cout << "printing it again.." << myStr;
 


Thanks, but I already know that the code will work if displayString accepts a string parameter.
The point is that I've get a bunch of legacy functions that accept const char * that I don't want to / can't change.
ie I'm hoping that this is a safe thing to do:
legacyFunction(getString().c_str());

instead of having to do this everywhere:
string sTemp = getString();
legacyFunction(sTemp.c_str());
Was This Post Helpful? 0
  • +
  • -

#4 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C++ scope of function return values

Posted 04 March 2010 - 09:47 PM

Hi gmcdonald73, I will attempt to answer your question for you.

using namespace std; 
 
string getString(); 
void displayString(const char * p); 
 
string getString() 
{ 
        string sVal = "TEST";                               <<<<<< Put the sVal variable on the stack ...
                                                            <<<<<< and assign a value "TEST"
        return sVal;                                        <<<<<< Set EAX register to contain ...
                                                            <<<<<< ... address of sVal (on the stack)
}                                                           <<<<<< Return to caller removing sVal ...
                                                            <<<<<< from the stack
                                                            <<<<<< Effectively sVal is no longer valid
                                                            <<<<<< as the stack pointer is above its
                                                            <<<<<< address
 
void displayString(const char * p) 
{ 
        printf("*** %s ***\n", p); 
} 
 
int _tmain() 
{ 
        // This seems to work - is this guaranteed?         <<<<<< absolutely NOT guarateed
        displayString(getString().c_str());  
 
        // This doesn't work - the string that is returned by getString() goes out of scope immediatiely after this line 
        const char * p2 = getString().c_str(); 
        displayString(p2);  
}



Without knowing assembler, this is difficult to explain in a way that really makes sense. If you have any questions please ask.

BTW I have commented the code but you will have to use the horizontal scroll to see them.

This post has been edited by Martyn.Rae: 04 March 2010 - 09:48 PM

Was This Post Helpful? 0
  • +
  • -

#5 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C++ scope of function return values

Posted 04 March 2010 - 09:50 PM

Really your question is, what is the life span of the return value of the std::string::c_Str() function -- good question. As far as I know it is good until the string changes.

To quote cplusplus.com:

Quote

this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

Was This Post Helpful? 0
  • +
  • -

#6 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C++ scope of function return values

Posted 04 March 2010 - 09:57 PM

@NickDMax, not true if the variable is created locally on the stack and the return value being a reference to it. You end up with a reference to an object that exists on the stack only until it is overwritten by any code that uses the stack space below the current stack pointer.
Was This Post Helpful? 0
  • +
  • -

#7 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C++ scope of function return values

Posted 04 March 2010 - 11:24 PM

I don't really see how that is "not true" or how scope really has anything to do with what I said... if the string is not in scope anymore and is destroyed then it has been modified.

Though I think you bring up a good point that one has to keep in mind that the return value of string::c_str() is tied to the life of the object -- in fact it is tied to the object, if that object leaves scope, or it is modified then the array pointed to by a previous call to c_str() will be invalid.
Was This Post Helpful? 0
  • +
  • -

#8 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C++ scope of function return values

Posted 04 March 2010 - 11:28 PM

Apologies NickDMax, I agree with you that when the object looses scope, it's integrity is destroyed, and yes that is modified I suppose. Many people though are blissfully unaware that this happens though. Just because they have not modified or destroyed it intentionally does not mean that it cannot be destroyed unintentionally.

This post has been edited by Martyn.Rae: 04 March 2010 - 11:30 PM

Was This Post Helpful? 0
  • +
  • -

#9 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C++ scope of function return values

Posted 04 March 2010 - 11:44 PM

Yes, for example people will do something like this:

const char* getStr() {
string a = "whatever";
return a.c_str();
}


The code looks innocent enough but since the string is no long in scope once the function ends the return value is no good. I have written code like this myself and been oh so terribly confused when it was not working. Actually with me it would be more something like this:

const char *ptr;
for(whatever) {
string s = "whatever";
ptr = s.c_str();
}
cout << ptr; //Crash....



This is the kind of thing that will get one in trouble if you don't understand scope! (which apparently I don't from time to time).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1