473,652 Members | 3,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

safe to return a 'const char *' from a local std::string?

Hi,

if i have a code

const char * GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}

Is the code above safe? I think not because the value 'szVectorValue' will
be released making the const char garbage.

i could do

std::string GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector
return szVectorValue;
}

but the problem is that i am using sprintf( ... )

and it would be simpler/clearer if instead of 'GetValue().c_s tr()' i could
do 'GetValue()'

Many thanks for your input.

Sims
Jul 22 '05 #1
7 3561
Użytkownik Sims napisał, On 2004-01-27 12:12:
Hi,

if i have a code

const char * GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}

Is the code above safe? I think not because the value 'szVectorValue' will
be released making the const char garbage.
This code isn't safe, szVectorValue is on stack and when you return from
this function it simply don't exists, so all you get is garbage...
i could do

std::string GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector
return szVectorValue;
}

but the problem is that i am using sprintf( ... )

and it would be simpler/clearer if instead of 'GetValue().c_s tr()' i could
do 'GetValue()'

If you don't want 'GetValue().c_s tr()' you could try something like this

const char * GetValue()
{
static std::string szVectorValue ;
szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}
but I'm not sure it is better solution than 'GetValue().c_s tr()'.
Best regards
Darek Ostolski
--
ld: bad magic number
Jul 22 '05 #2
> > std::string GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector return szVectorValue;
}

but the problem is that i am using sprintf( ... )

and it would be simpler/clearer if instead of 'GetValue().c_s tr()' i could do 'GetValue()'

If you don't want 'GetValue().c_s tr()' you could try something like this

const char * GetValue()
{
static std::string szVectorValue ;
szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}


Thanks.

But that's also on the stack so will also become garbage, won't it?

Sims
Jul 22 '05 #3
Użytkownik Sims napisał, On 2004-01-27 12:25:
const char * GetValue()
{
static std::string szVectorValue ;
szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}

Thanks.

But that's also on the stack so will also become garbage, won't it?

Sims


No it's static, so it isn't on stack, and you don't get garbage.
This static string is really bad idea. You have one szVectorValue in
your program, so if szVectorValue need to reallocate memory, you will
have garbage previously returned. This also means that if you call
GetValue two times, previously returned value will be 'magicly'
replaced with last returned value. Is is better idea to return copy of
std::string and call it by 'GetValue().c_s tr()'.

Best regards
Darek Ostolski
--
Windows: A thirty-two bit extension to a sixteen-bit patch to a
eight-bit operating system originally coded for a four-bit
microprocessor written by a two-bit company that can't stand one bit of
competition. [Jargon File 4.3.3]
Jul 22 '05 #4
Sims wrote:
>

If you don't want 'GetValue().c_s tr()' you could try something like this

const char * GetValue()
{
static std::string szVectorValue ;
szVectorValue = ...// get a std::string from the vector
return szVectorValue.c _str();
}


Thanks.

But that's also on the stack so will also become garbage, won't it?
...


No, it's 'static' which means that it is not on stack. However, in
general case writing non-reentrant functions is a bad idea unless you
have a good reason to do it. Personally, I wouldn't consider the above
problem to be a good reason for this type of trick.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #5
> >
But that's also on the stack so will also become garbage, won't it?
...


No, it's 'static' which means that it is not on stack. However, in
general case writing non-reentrant functions is a bad idea unless you
have a good reason to do it. Personally, I wouldn't consider the above
problem to be a good reason for this type of trick.


So do you also suggest i do 'GetValue().c_s tr()' rather than try to be lazy?

Sims
Jul 22 '05 #6
Sims wrote:
>
> But that's also on the stack so will also become garbage, won't it?
> ...


No, it's 'static' which means that it is not on stack. However, in
general case writing non-reentrant functions is a bad idea unless you
have a good reason to do it. Personally, I wouldn't consider the above
problem to be a good reason for this type of trick.


So do you also suggest i do 'GetValue().c_s tr()' rather than try to be lazy?
...


Yes. Using C standard library functions with C++ standard library
classes is supposed to be cumbersome, since this is not exactly a
natural combination :)

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #7
Sims wrote:
i could do

std::string GetValue()
{
std::string szVectorValue = ...// get a std::string from the vector
return szVectorValue;
}

but the problem is that i am using sprintf( ... )

Do you really need to use sprintf??? You can use ostringstream to do
string formatting, and you can forget about your .c_str() problems.

Just a though, I have no idea what you are trying to accomplish.

Jorge L
Jul 22 '05 #8

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

Similar topics

8
4572
by: Simon | last post by:
Hi, I think this is slightly OT, (I am not certain that Macros are part of the standard), but I am hopping that someone could help. I am trying to use a language file in my system. the format of the file would be something like open=Open
22
13240
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; char c; std::string str;
2
1926
by: anelma via .NET 247 | last post by:
Following code works fine, when compiled with VS 6.0, but not anymore when compiled in .NET. What's wrong here, I can't see it by myself? arrString content will be garbage with .net compilation, but when compiled with 6.0 it contains string from Vector (that's how I want it to work). std::vector<std::string> Vector; ... void MyClass::DoThis(std::vector<std::string> Vector) { const char *arrString;
6
2214
by: Hector Y. Martinez | last post by:
Well, here is my problem, I'm trying to convert an std::string variable to a char*, when I do std::string foo = "try something"; char* foo2 = foo.c_str(); an error ocurre, c_str() return a const char* not a char* how can I resolve this problem, what's the diference between const char* and char* and how can I obtatin a char* Thanx in advantage
3
4332
by: Rick Helmus | last post by:
Hello all In a few classes I have overloaded functions for C style strings and STL strings like this class SomeClass { void f(const char *s); void f(const std::string &s); };
6
7461
by: DaTurk | last post by:
Hi, I have several interfaces in CLI that I access via c#. My problem is, is that down in the unmanaged c++, which the CLI lies on top of, I have a lot of c_str() happening. But all of my methods in CLI return System::String^. I originally just gcnew'd System::String^ passing in the c_str(). But I can't really have as many gcnew's as I'm using for overhead and for fear of leaks. So my question is this, how can I get the char*...
2
3434
by: ragged_hippy | last post by:
Hi, If I have a method that has string reference as a parameter, what happens if I pass a const char* variable to this method? One thought is that a temporary string will be created in the stack and the parameter will refer to this object. Is this correct? Does this mean if a constructor of a class has a string reference parameter, the temporary string that is created in the stack is
1
3464
by: zottty | last post by:
Dear Friends, I don't even really know how to describe this problem. My base64 decoding algorithm doesn't work fine, because the result of the following lines is 0xffffffc5 instead of 0xc5. Please tell me how can I get in/out the string the original 0xc5 value and why is it going that way. Thank you! Zoltan The code:
5
1976
by: Olaf | last post by:
Hi, I wrap a legacy C library, e.g. the signature is void set_error_buffer(char* buf); where the buf length should be of length of 512 (it's defined). Now I want to wrap it with std::string. What is the prefered way?
0
8367
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
8589
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
6160
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
5619
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
4145
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2703
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
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
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.