Finding Invalid Static Casts

August 24, 2006

In Patternist, the XSL-T, XQuery and XPath framework, casting between class hierarchies is common, as in most other compiler software. For that reason, as discussed with Vincent, I added a class for simplifying this and making it safer. The doxygen documentation explains it all.

For me it brought an unexpected side effect: the asserts performing dynamic casts found two cases where the code performed invalid static casts. Previously, the code compiled, the code worked and tests passed. I knew the code paths were run. Nevertheless, the static casts were invalid because the values being cast were not instances of the target type.

Why did the casts work then? Hard to tell precisely, but it involved factors such as what compiler that was used, hardware platform, compiler switches and the layout of the classes. The reason being that the code the compiler generated for accessing the class instances happened to work even though the instances weren’t of the types the compiler was told.

Hence, having these dynamic_cast asserts are close to invaluable since they found two bugs that would first appear on another setup, which I wouldn’t be able to reproduce. Bugs, that probably first would be encountered in production code.

On large projects I think it is wise to use a mechanism such as CppCastingHelper. I wonder how many static source code analyzers that verifies static casts are valid.

3 Responses to “Finding Invalid Static Casts”

  1. jml Says:

    Out of curiousity, which were the offending compilers?

  2. englich Says:

    Not sure I’m following you, Jason.

    The casts worked on my setup(gcc 4.0.2), but probably could break on other setups. On case was that I was casting to one class but intended to do so to another one, but it happened to work because the classes were similar(!). This could break depending on compiler options, or source code changes, for example.

    In other words, I haven’t investigated what compilers that survive murky casts(but I assume most compilers can handle CppCastingHelper without trouble since it’s fairly standard, valid C++).

    Frans

  3. alfons Says:

    I don’t understand why you’d use QT for a C++ library. I also think parametrisation (templatizing) is the way to go, see one of the most impressive attempts to write an XSL library, the boost way:

    Arabica

    This guy is obviously a genius.


Leave a comment