The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Microsoft Code Quality

Code -

    CString strSet("1234567890");
    int pos = strSet.Find('\0');

    printf("%d", pos);

Guess what the result is?
Monday, May 21, 2007
Monday, May 21, 2007
1234567890 ?
Monday, May 21, 2007
Oh My bad, 10 of course ....
Monday, May 21, 2007
Is it -1?  The obvious answer is 10, so I'm guessing that the terminating NUL isn't counted as part of the string, which is why you're annoyed.
Monday, May 21, 2007
One of the nicest things about MFC/ATL is that they give you the source. Just looking at the code, I'd say you get a return value of 10.

Find is calling _mbschr, which is documented as including the terminating null in the search. This is an implementation detail that should be hidden from the user; CStrings are not documented as being null terminated. The proper return value should be -1.

Chalk up another one for "Leaky Abstractions".
Mark Ransom Send private email
Monday, May 21, 2007
On the other hand - it is kind of absurd: looking for zero in a CString. Never happens in real life application.
asmguru62 Send private email
Tuesday, May 22, 2007
It would easily happen if you were getting the CString from an external source, and wanted to be sure it could be a valid C-style string without being truncated.
Mark Ransom Send private email
Tuesday, May 22, 2007
I had to create a patch for this stupid issue. I store a set of characters in a CString object and compare input characters against this character set one by one to validate. It worked until a NUL character got into the input. Since the return value > 0, the character entered into processing and caused problems.

Microsoft doc says:

Return value:
The zero-based index of the first character in this CStringT object that matches the requested substring or characters; -1 if the substring or character is not found.

On the other side, STL string::find_first_of returned correct result.
Tuesday, May 22, 2007
This isnt a microsoft problem, its a programmer not knowing how to use the programming language problem I think :)

Strings in many languages are n+1 in length and should be null terminated (thats what the +1 means).

Also, if one is taking keyboard input, I think one should always check for special characters.  A test technique is called 'break testing' an application where one deliberately enters garbage data to see what the result would be.
Saturday, June 02, 2007

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz