473,698 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return C-style string from function?

#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.

Oct 23 '06 #1
10 6763

"howa" <ho******@gmail .comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.
When the function finishes the string s goes out of scope,
and, since its in the stack, it becomes garbage.

A quick fix is to change the line
return s.c_str();
to
return strdup(s.c_str( ) );

Serafeim
Oct 23 '06 #2
In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
"howa" <ho******@gmail .comwrote:
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.
const char* test( char* src ) {
return src;
}

--
To send me email, put "sheltie" in the subject.
Oct 23 '06 #3

Papastefanos Serafeim 寫道:
"howa" <ho******@gmail .comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.

When the function finishes the string s goes out of scope,
and, since its in the stack, it becomes garbage.

A quick fix is to change the line
return s.c_str();
to
return strdup(s.c_str( ) );

Serafeim
Thanks...

is this a usual/normal way to pass a string out of a function?

Oct 23 '06 #4
"howa" <ho******@gmail .comwrote:
Papastefanos Serafeim wrote:
>"howa" <ho******@gmail .comwrote:
>>#include <iostream>

using namespace std;

const char* test(char *src) {
string s(src);
return s.c str();
}

int main() {
char src[] = "test123";
cout<<test(src) ;
return 0;
}

how to get the "test123" from the function?

thanks.

When the function finishes the string s goes out of scope,
and, since its in the stack, it becomes garbage.

A quick fix is to change the line
return s.c str();
to
return strdup(s.c str() );

Serafeim

Thanks...

is this a usual/normal way to pass a string out of a function?
No. strdup isn't even defined in the language. The usual way to do it is
by returning a string that was passed in. See: strcpy for an example.

--
To send me email, put "sheltie" in the subject.
Oct 23 '06 #5
howa wrote:
is this a usual/normal way to pass a string out of a function?
No, this is just a way to stop using RAII, hence creating non
exception-safe code and a memory leak in various situations.
This also has many other obvious problems related to pointers.
Oct 23 '06 #6
howa posted:
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

The memory which the string occupies must still be accessible after the
funciton returns. Therefore, either:

(1) Have the calling function allocate the memory, and pass a pointer so
that the called function will alter the memory.

(2) Have the called function allocate the memory dynamically, and return a
pointer which the calling function shall have to delete.

(3) Use global/static data...

--

Frederick Gotham
Oct 23 '06 #7
howa wrote:
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.
const char* test(char *src)
{
return src;
}

OR

const char* test(char *src)
{
static string s(src);
return s.c_str();
}

OR

const char* test(char *src)
{
string* s = new string;
*s = src;
return s->c_str();
}

Best regards,
-Martin

Oct 23 '06 #8
const char* test(char *src)
{
string* s = new string;
*s = src;
return s->c_str();
}
I forgot to tell you: that's not good,
because I create a memory leak here.
String s cannot be deleted anywhere.

-Martin

Oct 23 '06 #9
"howa" <ho******@gmail .comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
#include <iostream>

using namespace std;

const char* test(char *src) {

string s(src);

return s.c_str();
}

int main() {

char src[] = "test123";

cout<<test(src) ;

return 0;
};

how to get the "test123" from the function?

thanks.
You're going to have problems no matter what method you decide to return a
c-style string. The best solution is to return a std::string. That's why
std::strings were invented, to get rid of this problem. What can returning
a c-style string get you that returning a std::string can't?
Oct 23 '06 #10

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

Similar topics

4
23493
by: Paul | last post by:
Hi, In SQL Books Online in the section on @@Error it gives the following example: -- Execute the INSERT statement. INSERT INTO authors (au_id, au_lname, au_fname, phone, address, city, state, zip, contract) values (@au_id,@au_lname,@au_fname,@phone,@address,
2
4664
by: Rhino | last post by:
I am trying to verify that I correctly understand something I saw in the DB2 Information Center. I am running DB2 Personal Edition V8.2.1 on Windows. I came across the following in the Info Center: To return a result set from a procedure to the originating application, use the WITH RETURN TO CLIENT clause. When WITH RETURN TO CLIENT is specified on a result set, no nested procedures can access the result set.
1
4674
by: Jack Addington | last post by:
I have a 3rd party object that fires an itemchanged event when someone edits some data on a form. This event has a custom eventArgs that has a field called ActionCode. In the code of the event, if you set this ActionCode to various values the control will respond in various ways (reject, reject change field, accept, etc). I am trying to understand exactly how that works as I am trying to extend the control and add more processing s...
2
5552
by: 6kjfsyg02 | last post by:
I am trying to return one of two different objects from the same method, but I can not do it in WSDL or C#. I have a web service with three methods. I have been told that one of the methods must return either <Respuesta ....> or <ConfirmacionPeticion ...> directly under the SOAP Body. Other methods are already capable of returning just <Respuesta ...> or just <ConfirmacionPeticion ...>. What is new is one method being capable of...
6
2549
by: miked | last post by:
Why are there still no covariant return types? All searches reveal no workarounds accept for using an interface which is a real pain. I wind up missing this capability almost every time I inherit a class. The best workaround and one that I use is the new keyword and cast the base class reference, but in my opinion this is a bad practice leading to error prone code. Can someone from MS chime in on this and provide some feedback?
14
20963
by: tshad | last post by:
Is there any difference between Return and Exit Sub? I have some code that uses both when I have an error in my Sub. Thanks, Tom
8
1639
by: WakeBdr | last post by:
I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc)
9
4007
by: Alexander Widera | last post by:
hi, is it possible to return an object of an unknown (but not really unknown) type with an method? i have the following situation: - a variable (A) of the type "object" which contains the object - a variable (B) of the type "Type" which contains the type of the object in (A) (A should be of the type B) - a method which should return the object (A) as type (B)
0
1309
by: terminator(jam) | last post by:
Since delaration of C++ the r/l-valueness of objects has been source of confusion there are some actions that can perform on lvalues but not on rvalues , especifically on initrinsic types .BTW the programmer is not capable of defining special interface for classes based on the r/l-valueness of the object(the way we do for const/volatile).Move proposal - about Hot(rvalue) refernce - has been an attempt to get that different behavior at...
4
2025
by: fabian.lim | last post by:
Hi All, Im a newbie to C++, I am trying to customize the vector template STL to a template Class. My code is shown below. Im confused about something and maybe somebody here might be able to help me. Lets say X is my vector, which contains 10 elements. I want to assign elements indexed 2 to 5 to another vector Y, so I want to do it like Y = X(2,5). So what I do is i overload the () operators, as marked in (a) below. This creates a new...
0
8678
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9166
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
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
8899
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
8871
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...
0
7737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5861
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();...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.