Code:cstr[ getLastCharIndex(cstr) + 1 ] = '\0'; str.assign( cstr );Why does the latter inject garbage into my strings?Code:str.assign( cstr, getLastCharIndex(cstr) + 1 );
Code:cstr[ getLastCharIndex(cstr) + 1 ] = '\0'; str.assign( cstr );Why does the latter inject garbage into my strings?Code:str.assign( cstr, getLastCharIndex(cstr) + 1 );
The latter assigns one more (uninitialized?, null?) character to the string than cstr has. Null-terminator is not part of std::strings.
Also, how does getLastCharIndex work if the string is not null-terminated?
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
cstr is not null terminated (the length of the string is stored instead). The latter gets the index i of the last char and tells assign to copy i+1 characters starting from cstr.
I've verified getLastCharIndex returns proper indices. It seems that assign doesn't like non-null-terminated char arrays??
If getLastCharIndex returns the same value as strlen (if the string was null-terminated) are you not assigning one more character than there is in the second version?
In the first version, yes the string obviously has to be null-terminated, because otherwise assign wouldn't know how long it is.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
getLastCharIndex returns the index of the last character, which would be equivalent to (strlen - 1) (keep in mind, no null-char here). In the first example, I allocated one extra byte for cstr to be able to assign the '\0'.
Basically, if the string is "bar", then getLastCharIndex returns 2 (the index offset of 'r') and so assigning getLastCharIndex()+1 characters should copy the entire string and nothing more, yet I have no idea where the garbage is coming from?? I can verify the index is correct because the first example writes the null character to the correct address.
Last edited by @nthony; 11-06-2008 at 02:16 AM.
Actually I think I just found some larger problems in the ADT surrounding getLastCharIndex that may be causing this. I'll investigate some more. Thanks! and sorry for wasting your time.
What happens if you remove the +1?Code:str.assign( cstr, getLastCharIndex(cstr) + 1 );
"I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008
"the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010