473,853 Members | 1,984 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange behavior with Standard C++ 'string' objects

Hello,

I'm new to the boards, and I've been struggling with a problem porting my
company's code from Visual C++ 6.0 to Visual C++ 2005.

We've found some crashes that I've traced to the 'c_str()' member of the
standard string class. I've debugged into the deepest layers of the system
code and cannot explain this.

What we have is a class with a private 'string' member:

string _linkType;

And public function that returns it:

class Link
....
string getLinkType() const {return _linkType; }

When attempting to access the string as a char * later in the code, the
resulting string "1M" does not get extracted properly:

Link *ilink;
const char *pLinkType;
pLinkType = ilink->getLinkType(). c_str();

The result of this is that pLinkType is "".

Now - here's the weird part.

const char *blah;
string strvalue;
strvalue = ilink->getLinkType( );
blah = strvalue.c_str( );

If I do this, 'blah' contains the proper string '1M'.

How can this be? If I break apart the operation into two lines, it works.
Keep it as one line and it fails!?

I've tried defining the member as std::string and return value from the get
function as std::string as well, with no change in behavior. I'd really
like a good solution to this, as this example literally shows up hundreds of
times in our code. It would be a lot of work to make the massive changes to
ensure the proper value is getting returned.

This works just fine in Visual C++ 6.0. I've even installed VC++2005 SP1 to
see if it was fixed there, with no change.

Thanks so much in advance for your help!
Mar 8 '07 #1
7 1763
Brian Kunz wrote:
Hello,

I'm new to the boards, and I've been struggling with a problem
porting my company's code from Visual C++ 6.0 to Visual C++ 2005.

We've found some crashes that I've traced to the 'c_str()' member of
the standard string class. I've debugged into the deepest layers of
the system code and cannot explain this.

What we have is a class with a private 'string' member:

string _linkType;

And public function that returns it:

class Link
....
string getLinkType() const {return _linkType; }

When attempting to access the string as a char * later in the code,
the resulting string "1M" does not get extracted properly:

Link *ilink;
const char *pLinkType;
pLinkType = ilink->getLinkType(). c_str();

The result of this is that pLinkType is "".
This produces a pointer into a temporary return value, which disappears at
the semi-colon.
>
Now - here's the weird part.

const char *blah;
string strvalue;
strvalue = ilink->getLinkType( );
blah = strvalue.c_str( );

If I do this, 'blah' contains the proper string '1M'.
Because "1M" is saved inside strvalue, and blah points to that value. blah
is valid as long at strvalue doesn't change.
>
This works just fine in Visual C++ 6.0.
No it didn't. It just seemed to work. :-)
I've even installed VC++2005
SP1 to see if it was fixed there, with no change.
That's a good idea anyway.

Bo Persson
Mar 8 '07 #2
Brian Kunz wrote:
Link *ilink;
const char *pLinkType;
pLinkType = ilink->getLinkType(). c_str();

The result of this is that pLinkType is "".
What happens here is that getLinkType() returns a temporary object.
You're not storing it anywhere, so it gets destructed as soon as the
assignment is executed. c_str() is getting a pointer to a member of this
temporary string. When the string returned by getLinkType() goes out of
scope, the const char* returned by c_str() gets invalidated too.
const char *blah;
string strvalue;
strvalue = ilink->getLinkType( );
blah = strvalue.c_str( );

If I do this, 'blah' contains the proper string '1M'.
That works as expected, since the string returned by getLinkType is no
longer a temporary. You have a local copy of it, so blah will be valid
as long as strvalue is alive. However, as soon as strvalue goes out of
scope, the value of blah will become undefined.
How can this be? If I break apart the operation into two lines, it works.
Keep it as one line and it fails!?
It's not a matter of having 1 line or 2 lines, it has to do with the
temporary. You have to remember that unless you declare a variable and
give a name to it, it's nothing more than a temporary that dies at the
end of the instruction (when the semicolon is closed). Getting a pointer
to a temporary, or one of its members, is pretty dagerous an unpredictable.

In VC6 the compiler didn't immediately destroy your temporary, so your
pointer was still alive. However, there's no such guarantee. You were
exploiting undefined behavior, and with VC++ 2005 your luck has turned
around. In fact, you should be happy that you caught a bug, because it
was always hanging in the air, waiting for an accident to happen.

Tom
Mar 8 '07 #3
Thank you both so much for your help. What you're saying makes complete
sense. I guess that fact that it worked in 6.0 led me to believe a change in
behavior. Bottom line is, we got lucky and our luck ran out.

Thanks again!

"Tamas Demjen" wrote:
Brian Kunz wrote:
Link *ilink;
const char *pLinkType;
pLinkType = ilink->getLinkType(). c_str();

The result of this is that pLinkType is "".

What happens here is that getLinkType() returns a temporary object.
You're not storing it anywhere, so it gets destructed as soon as the
assignment is executed. c_str() is getting a pointer to a member of this
temporary string. When the string returned by getLinkType() goes out of
scope, the const char* returned by c_str() gets invalidated too.
const char *blah;
string strvalue;
strvalue = ilink->getLinkType( );
blah = strvalue.c_str( );

If I do this, 'blah' contains the proper string '1M'.

That works as expected, since the string returned by getLinkType is no
longer a temporary. You have a local copy of it, so blah will be valid
as long as strvalue is alive. However, as soon as strvalue goes out of
scope, the value of blah will become undefined.
How can this be? If I break apart the operation into two lines, it works.
Keep it as one line and it fails!?

It's not a matter of having 1 line or 2 lines, it has to do with the
temporary. You have to remember that unless you declare a variable and
give a name to it, it's nothing more than a temporary that dies at the
end of the instruction (when the semicolon is closed). Getting a pointer
to a temporary, or one of its members, is pretty dagerous an unpredictable.

In VC6 the compiler didn't immediately destroy your temporary, so your
pointer was still alive. However, there's no such guarantee. You were
exploiting undefined behavior, and with VC++ 2005 your luck has turned
around. In fact, you should be happy that you caught a bug, because it
was always hanging in the air, waiting for an accident to happen.

Tom
Mar 8 '07 #4
In article <F0************ *************** *******@microso ft.com>,
=?Utf-8?B?QnJpYW4gS3V ueg==?= <Br*******@disc ussions.microso ft.comwrote:
>Thank you both so much for your help. What you're saying makes
complete sense. I guess that fact that it worked in 6.0 led me to
believe a change in behavior. Bottom line is, we got lucky and our
luck ran out.
I think you're going to find that 2005 is a real nitpicker when it
comes to sketchy code. I much prefer things to fail instantly and
obviously, rather than being lucky.

Nathan Mates

--
<*Nathan Mates - personal webpage http://www.visi.com/~nathan/
# Programmer at Pandemic Studios -- http://www.pandemicstudios.com/
# NOT speaking for Pandemic Studios. "Care not what the neighbors
# think. What are the facts, and to how many decimal places?" -R.A. Heinlein
Mar 8 '07 #5

"Brian Kunz" <Br*******@disc ussions.microso ft.comwrote in message
news:F0******** *************** ***********@mic rosoft.com...
Thank you both so much for your help. What you're saying makes complete
sense. I guess that fact that it worked in 6.0 led me to believe a change
in
behavior. Bottom line is, we got lucky and our luck ran out.
This is the fix you are probably looking for, that won't require a million
changes to scattered code:

class Link
....
const std::string& getLinkType() const {return _linkType; }

pLinkType = ilink->getLinkType(). c_str(); // now OK
Mar 8 '07 #6


"Ben Voigt" wrote:
This is the fix you are probably looking for, that won't require a million
changes to scattered code:

class Link
....
const std::string& getLinkType() const {return _linkType; }

pLinkType = ilink->getLinkType(). c_str(); // now OK
YES YES! Perfect! That works wonderfully, thank you so much.
Mar 8 '07 #7

"Brian Kunz" <Br*******@disc ussions.microso ft.comwrote in message
news:06******** *************** ***********@mic rosoft.com...
>

"Ben Voigt" wrote:
>This is the fix you are probably looking for, that won't require a
million
changes to scattered code:

class Link
....
const std::string& getLinkType() const {return _linkType; }

pLinkType = ilink->getLinkType(). c_str(); // now OK
YES YES! Perfect! That works wonderfully, thank you so much.
Note that the string object is now the actual member variable, so the
lifetime is now equal to the lifetime of the object ilink refers to. That's
probably long enough for all callers, but it might not always be.
Mar 9 '07 #8

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

Similar topics

36
3467
by: Dmitriy Iassenev | last post by:
hi, I found an interesting thing in operator behaviour in C++ : int i=1; printf("%d",i++ + i++); I think the value of the expression "i++ + i++" _must_ be 3, but all the compilers I tested print 2.
13
1879
by: Neil Zanella | last post by:
Hello, I wonder whether anyone has ever come across the following g++ compiler error message. I don't recall ever seeing it before. I solved my problem but I am still not sure about what this message is all about. Any ideas? error: invalid initialization of non-const reference of
31
6659
by: Bjørn Augestad | last post by:
Below is a program which converts a double to an integer in two different ways, giving me two different values for the int. The basic expression is 1.0 / (1.0 * 365.0) which should be 365, but one variable becomes 364 and the other one becomes 365. Does anyone have any insight to what the problem is? Thanks in advance. Bjørn
6
2284
by: Joseph Geretz | last post by:
Writing an Outlook AddIn with C#. For the user interface within Outlook I'm adding matching pairs of Toolbar buttons and Menu items. All of the buttons and menu items are wired up to send events to the same method (aka delegate?). I use the Tag property within this method to determine what user action is taking place. Very simple: When adding toolbar button: tbButton.Click += new...
3
1523
by: sara | last post by:
Very strange behavior, but I suspect some is A2K and some might be for me to correct. Just trying to see if anyone can help and advise. We have a database that's been running for a few years with no problems. We continuously add queries and reports. We're up to about 700 queries (no, not all are used and most are parameter queries - the business asks a LOT of questions!), and under 250 reports and fewer than 15 forms. Data is...
1
2983
by: Nicholas Palmer | last post by:
Hi all, Got a question about the AspCompat=true page property. First a little background. We have an ASP.NET app that uses two COM components. The first is the Microsoft OWC 11 components and the second is a custom VB6 COM component. So I was reading about AspCompat=true and it seemed like it would be a good fit for our app. From what I can tell both of the COM components that we are using are STA and we are creating the components in...
8
3228
by: FBM | last post by:
Hi there, I am puzzled with the behavior of my code.. I am working on a networking stuff, and debugging with eclipse (GNU gdb 6.6-debian).. The problem I am experiencing is the following: Whenever I declare the sockaddr_in structure inside the main, the debugger crashes at line X*, not being able to access argv parameters (see code below). It is very strange.. by only being there, sockaddr_in does not allow me to question argc...
160
5945
by: DiAvOl | last post by:
Hello everyone, Please take a look at the following code: #include <stdio.h> typedef struct person { char name; int age; } Person;
20
2253
by: Pilcrow | last post by:
This behavior seems very strange to me, but I imagine that someone will be able to 'explain' it in terms of the famous C standard. -------------------- code ----------------------------------- #include <stdio.h> int main (void) { char xx="abcd"; char * p1 = xx;
0
9898
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
9748
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
11020
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
10670
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...
0
9506
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...
0
7074
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
5736
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...
1
4549
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
2
4143
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.