May 182009

Never access an std::string‘s buffer with an intent to increase/decrease it’s length nor pass such a buffer to functions which takes a char*. I did this mistake sometime back and got trapped in a strange bug with operator +=. This is how my code looked.

std::string str( ' ', MAX_PATH );
GetFolderName( pFullPath, &str[0] ); // Oop

Problem with above code is that you won’t get an immediate crash since it’s a properly allocated buffer with MAX_PATH chars. But if you do further operations on such string expect plenty of inconsistencies. This is how my code looked after above piece of code…

str += "\\"; // Append backslash

I was expecting a valid path with backslash appended towards it’s end, but this never happened and debugging with debugger too didn’t help.

So now let me tell you what the exact problem is! When you do &str[0] you pass the address to the first char in std::string‘s buffer. So when function GetFolderName fills in this buffer with folder path the length of std::string is not updated since it’s a C style function and it’s neither expected to do so. So the function terminates given buffer with a ” with std::string‘s length way high (MAX_PATH). So now when I do a += std::string internally fails some condition leading to unexpected results, note that this piece of code never caused a crash but I was quite lucky and watchful enough to fix this stupid bug. Sigh!

So watchout, there is no CString::GetBuffer or CString::GetBufferSetLength type of function for std::string, well at least for now.


Leave a Reply