std::string assignment from const char* longer than 16 characters causes junk

B

Ben Harper

In VC7, look at the following code:

char* ok1 = "1234567890ABCD";
char* ok2 = "1234567890ABCDE";
char* bad1 = "1234567890ABCDEF";
char* bad2 = "1234567890ABCDEFG";
string take;
take = ok1;
take = ok2;
take = bad1;
take = bad2;

Debug it and inspect take after take = bad1 and take = bad2. take is filled
with garbage!!!
If the const char* string is longer than 15 characters then the resulting
std::string is junk.

On VC7.1 it is fixed.

Is there a workaround? I searched on google groups but couldn't find
anything. This is a painful and glaring bug. I'm forced to suspect that it
may be my setup, but I can't see why that would be..

Please help! Must I rewrite std::string ????
 
T

Tomas Restrepo \(MVP\)

Ben,
In VC7, look at the following code:

char* ok1 = "1234567890ABCD";
char* ok2 = "1234567890ABCDE";
char* bad1 = "1234567890ABCDEF";
char* bad2 = "1234567890ABCDEFG";
string take;
take = ok1;
take = ok2;
take = bad1;
take = bad2;

Debug it and inspect take after take = bad1 and take = bad2. take is filled
with garbage!!!
If the const char* string is longer than 15 characters then the resulting
std::string is junk.

On VC7.1 it is fixed.

Is there a workaround? I searched on google groups but couldn't find
anything. This is a painful and glaring bug. I'm forced to suspect that it
may be my setup, but I can't see why that would be..

Please help! Must I rewrite std::string ????

No. The problem is only on the debugger, not at runtime. This happens
because for VC7, std::string was rewritten so that it includes internally a
union used to store inline strings with 15 or fewer chars, or a pointer to
heap allocated space if it's larger, and the debugger only looked at the
first part.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top