...
The macro
offsetof(type, member-designator)accepts a restricted set of type arguments in this International Standard. If type is not a standard-layout class, the results are undefined. The expressionoffsetof(type, member-designator)is never type-dependent and it is value-dependent if and only if type is dependent. The result of applying theoffsetofmacro to a field that is a static data member or a function member is undefined. No operation invoked by theoffsetofmacro shall throw an exception andnoexcept(offsetof(type, member-designator))shall be true.
When specifying the type argument for the offsetof() macro, pass only a standard-layout class. The full description of a standard-layout class can be found in paragraph 7 of the [class] clause of the C++ Standard, or the type can be checked with the std::is_standard_layout<> type trait. When specifying the member designator argument for the offsetof() macro, do not pass a bit-field, static data member, or function member. Passing an invalid type or member to the offsetof() macro is undefined behavior.
Noncompliant Code Example
In this noncompliant code example, a type that is not a standard-layout class is passed to the offsetof() macro, resulting in undefined behavior.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <cstddef>
struct D {
virtual void f() {}
int i;
};
void f() {
size_t off = offsetof(D, i);
// ...
} |
...
In this noncompliant code example, the offset to i is calculated so that a value can be stored at that offset within buffer. However, because i is a static data member of the class, this example results in undefined behavior. According to the C++ Standard, [class.static.data], paragraph 1 [ISO/IEC 14882-2014], static data members are not part of the subobjects of a class.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Axivion Bauhaus Suite |
| CertC++-EXP59 | |||||||
| Clang |
|
| Emits an error diagnostic on invalid member designators, and emits a warning diagnostic on invalid types. | ||||||
| CodeSonar |
| BADMACRO.OFFSETOF | Use of offsetof | ||||||
| GCC |
|
| Emits an error diagnostic on invalid member designators, and emits a warning diagnostic on invalid types. | ||||||
| Helix QAC |
| C++3915, C++3916 | |||||||
| Parasoft C/C++test |
| CERT_CPP-EXP59-a | Use offsetof() on valid types and members | ||||||
| Polyspace Bug Finder |
| CERT C++: EXP59-CPP | Checks use of offsetof macro with nonstandard layout class (rule fully covered) |
...