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 );
Printable View
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?
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.
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.
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 );