PRB: offsetof() Macro Fails with Virtual Base Class (122217)
The information in this article applies to:
- Microsoft Visual C++, 32-bit Editions 1.0
- Microsoft Visual C++, 32-bit Editions 2.0
- Microsoft Visual C++, 32-bit Editions 4.0
- Microsoft Visual C++, 32-bit Editions 4.1
- Microsoft Visual C++, 32-bit Editions 4.2
This article was previously published under Q122217 SYMPTOMS
Use of the offsetof() macro may cause the compiler to generate incorrect
code when used with classes that have virtual base classes. This incorrect
code results in a null pointer access, which causes an access violation
when the application is executed.
This problem occurs only for members declared in the virtual base class.
Note that according to the ANSI C++ Draft Working Papers, clause 18.1.5,
the offsetof macro is restricted to POD union and POD structure types.
POD types may not have base classes. Using the macro contrary to this
restriction results in undefined behavior.
RESOLUTION
The offsetof() macro returns the offset in bytes of a member from the
beginning of a class by casing NULL to a pointer of class/struct type. To
work around this problem, cast the address of the object to a char *, cast
the address of the member to a char *, and subtract the address of the
object from the address of the member. Please see the Sample Code in the
MORE INFORMATION section for an example.
While this workaround generates code that is as efficient as the offsetof()
macro, it does require that the class/struct be instanced, while offsetof()
does not.
STATUS
This is by design.
Modification Type: | Minor | Last Reviewed: | 7/5/2005 |
---|
Keywords: | kbCodeGen kbCompiler kbCPPonly kbprb KB122217 |
---|
|