473,748 Members | 2,243 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 3574
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
4577
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
13327
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
1938
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
2217
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
4336
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
7468
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
3439
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
3468
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
1983
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
8979
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
8818
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
9522
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
9225
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
8234
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 project—planning, coding, testing, and deployment—without 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...
1
6790
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
6069
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
4589
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
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.