Take the following code:
CString str1("Startt"), str2("Start\0"); str1.SetAt(str1.GetLength()-1, '\0'); str1 += "End"; str2 += "End";
This is a simplified version of a much dirtier, very real bug I dealt with recently. Several string and debugger features joined forces to cause this behaviour.
First – the debugger: it apparently watches CStrings as c-strings – displaying their essentially-LPTSTR member m_pszData. Thus, any null embedded in the string (well, the first null, really) is treated as a terminating null – anything past it would not be displayed. When we force a watch on the full CString buffer, a fuller picture is revealed:
So the ‘End’ suffix was added to str1 after all – but why the difference between str1 and str2? How can initializing a string with an embedded null be any different than setting that null in the next line? The next clue is obtained by observing GetLength() for both strings. Note that GetLength returns the length of the allocated string buffer, not the strlen of the underlying c-string. (It is utterly unimaginable that such a basic behaviour goes undocumented.)
CString str1("Startt"), str2("Start\0"); int len1 = str1.GetLength(), // gives 6 len2 = str2.GetLength(); // gives 5 !
The issue now has nowhere left to hide. Stepping with the debugger into the CString ctors reveals the root cause: the constructor used for both CStrings accepts a char*-type as argument (in retrospect – how could it be otherwise?). So, just like in the debugger itself, the first embedded null is treated as a terminating null – anything past it would never make it into the CString. Try the following and see for yourself:
CString str3("First\0Second"); // str3 now contains only "First" !
Once this root cause was understood, the bug was a half-line fix.
Thanks and kudos go to Alexander M. of wordpress support, who found and fixed within 1 hour (!) a wordpress bug that I reported, to make this post possible: until yesterday, wordpress would ignore explicit nulls (backslash + zero) between quotes, in a sourcecode section.