473,781 Members | 2,491 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this work? (returning automatic string)

#include <cstring>
#include <iostream>
#include <string>

std::string foo()
{
char buf[16];

strcpy(buf, "this is a test.");

return std::string(buf );

}

int main()
{
std::cout << foo();

return 0;
}

it appears to me that foo should return garbage. however, "this is a test"
is printed correctly.
what am i missing here?

thanks in advance,
bryan
Jul 22 '05 #1
9 1814
Bryan Bullard wrote:
strcpy(buf, "this is a test.");
Here we copy 'this is a test\0' string to buf. (Note that the string
will be null terminated.)
return std::string(buf );
And here we return the null terminated string.
}

int main()
{
std::cout << foo();


And here we print it.

Everything looks fine to me. Why shouldn't this work?
Jul 22 '05 #2
Bryan Bullard wrote:
std::string foo()
{
char buf[16];
strcpy(buf, "this is a test.");
return std::string(buf );

} it appears to me that foo should return garbage. however, "this is a test" is printed correctly.
what am i missing here?


Google for "copy constructor". Then run that code thru the debugger and
trace inside the return statement to see one in action.

(Introductory C texts warn if you return buf, a character array, you get
undefined behavior; that's probably what you accidentally expected here.)

--
Phlip
Jul 22 '05 #3
Bryan Bullard wrote:

#include <cstring>
#include <iostream>
#include <string>

std::string foo()
{
char buf[16];

strcpy(buf, "this is a test.");

return std::string(buf );
This creates a std::string object.
Since the return type of this function specifies
std::string (and not a reference or a pointer) a
*copy* of that object is passed back to main.

}

int main()
{
std::cout << foo();
and here the std::string object returned from foo
is used for doing the output. Since the return value
of foo isn't used anywhere else, the temporary object
returned by foo is destroyed after the statement has
executed.

return 0;
}


--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4
Aggro wrote:
Bryan Bullard wrote:
strcpy(buf, "this is a test.");

Here we copy 'this is a test\0' string to buf. (Note that the string
will be null terminated.)
return std::string(buf );

And here we return the null terminated string.


No, "we" don't. We return a std::string object, which happens to be
constructed from a null-terminated sequence of characters.
}

int main()
{
std::cout << foo();

And here we print it.


Here we print a copy of the std::string returned by the function.

A std::string object isn't an array, although it may contain one. The
local object in the function is destroyed when the function returns, as
the OP expects. The value is copied to the caller's space, though, and
the copy can be printed, assigned, or whatever else one can do with a
string. This is the same thing that happens for other copy-by-value
types, e.g. int's.

Everything looks fine to me. Why shouldn't this work?


Jul 22 '05 #5

"Aggro" <sp**********@y ahoo.com> wrote in message
news:9B******** *******@read3.i net.fi...

thanks for your post.

you make a point that the string is null terminated. however, i don't be
that should make a difference.

char buf[16]; // is automatic storage
strcpy(buf, "..."); // copies the literal into the automatic storage.
return std::string(buf ); // constructes std::string based on automatic
storage.

does std::string create its own static copy? otherwise, it would seem to me
to be invalid.

-bryan

Bryan Bullard wrote:
strcpy(buf, "this is a test.");


Here we copy 'this is a test\0' string to buf. (Note that the string
will be null terminated.)
return std::string(buf );


And here we return the null terminated string.
}

int main()
{
std::cout << foo();


And here we print it.

Everything looks fine to me. Why shouldn't this work?

Jul 22 '05 #6

"Phlip" <ph*******@yaho o.com> wrote in message
news:ow******** *********@newss vr16.news.prodi gy.com...

thanks for the clarification.
Bryan Bullard wrote:
std::string foo()
{
char buf[16];
strcpy(buf, "this is a test.");
return std::string(buf );

}

it appears to me that foo should return garbage. however, "this is a

test"
is printed correctly.
what am i missing here?


Google for "copy constructor". Then run that code thru the debugger and
trace inside the return statement to see one in action.

(Introductory C texts warn if you return buf, a character array, you get
undefined behavior; that's probably what you accidentally expected here.)

--
Phlip

Jul 22 '05 #7

"Bryan Bullard" <th************ ********@sbcglo bal.net> wrote in message
news:hM******** **********@news svr23.news.prod igy.com...

my question was answered, thanks.

"Aggro" <sp**********@y ahoo.com> wrote in message
news:9B******** *******@read3.i net.fi...

thanks for your post.

you make a point that the string is null terminated. however, i don't be
that should make a difference.

char buf[16]; // is automatic storage
strcpy(buf, "..."); // copies the literal into the automatic storage.
return std::string(buf ); // constructes std::string based on automatic
storage.

does std::string create its own static copy? otherwise, it would seem to me to be invalid.

-bryan

Bryan Bullard wrote:
strcpy(buf, "this is a test.");


Here we copy 'this is a test\0' string to buf. (Note that the string
will be null terminated.)
return std::string(buf );


And here we return the null terminated string.
}

int main()
{
std::cout << foo();


And here we print it.

Everything looks fine to me. Why shouldn't this work?


Jul 22 '05 #8
Bryan Bullard wrote:

"Aggro" <sp**********@y ahoo.com> wrote in message
news:9B******** *******@read3.i net.fi...

thanks for your post.

you make a point that the string is null terminated. however, i don't be
that should make a difference.

char buf[16]; // is automatic storage
strcpy(buf, "..."); // copies the literal into the automatic storage.
return std::string(buf ); // constructes std::string based on automatic
storage.

does std::string create its own static copy?


Yes it does.

And please: Don't top post. Put your reply beneath the text
you are replying to.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #9
"Bryan Bullard" <th************ ********@sbcglo bal.net> wrote in
news:hM******** **********@news svr23.news.prod igy.com:

"Aggro" <sp**********@y ahoo.com> wrote in message
news:9B******** *******@read3.i net.fi...

thanks for your post.

you make a point that the string is null terminated. however, i don't
be that should make a difference.

char buf[16]; // is automatic storage
strcpy(buf, "..."); // copies the literal into the automatic storage.
return std::string(buf ); // constructes std::string based on
automatic storage.

does std::string create its own static copy? otherwise, it would seem
to me to be invalid.


Yes, std::string takes its own copy of the array into its own storage.

So your function will construct a string from the array, copy that string
into some temporary variable (to carry the return-by-value for your
function), which is then output via cout. (Some copies may be skipped due
to RVO).
Jul 22 '05 #10

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

Similar topics

6
1712
by: JKop | last post by:
unsigned int CheesePlain(void) { unsigned int const chalk = 42; return chalk; } unsigned int& CheeseRef(void) {
8
2559
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
74
4057
by: Suyog_Linux | last post by:
I wish to know how the free()function knows how much memory to be freed as we only give pointer to allocated memory as an argument to free(). Does system use an internal variable to store allocated memory when we use malloc(). Plz help......
3
3331
by: Jim Hsu | last post by:
when I use the XmlWebSerivce to response the xmlelement to Web Service client. the ASP.net plumbing work ( the XmlSerializer in WebServices ) will serialize the XML if we can control the wrapper class , I can set the XmlSchemaForm.None or Qualified so that there will no be a 'xmlns=""' in the following namespace, but I don't know how to do that in WebService plumbing. this null namespace will makes my web service wrapper class complains....
6
1909
by: EvilOldGit | last post by:
const Thing &operator++(int) { Thing temp = *this; operator++(); return temp; } Is this code robust ? I get a compiler warning about returning a reference to a a local, which I guess is because the compiler doesn't tell the difference between this overload any any other function.
8
2220
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
7
1253
by: Author | last post by:
I wrote a simple Person class with Visual C# 2008 Express Edition, in which I define two properties: FirstName and LastName. If I use the new c# automatic property feature, it *compiles with no problem*, but I don't get the value through the property. If I use the regular old style property definition, then it works perfect. // does not work
2
1655
by: vikassawant | last post by:
hi, I write one file with two buttons.Code for that is as fallow. public void actionPerformed(ActionEvent e) { try { if(e.getSource()==cancel) {
1
3656
by: sva0008 | last post by:
i have a auto suggest script that does not work in firefox , works great on IE. /******************************************************* AutoSuggest - a javascript automatic text input completion component Copyright (C) 2005 Joe Kepley, The Sling & Rock Design Group, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software...
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10143
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10076
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9939
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7486
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6729
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2870
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.