Use of the offsetof macro
ID |
c.maintainability.avoid_offsetof |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Type Safety |
Language |
C / C++ |
Rationale
offsetof is only guaranteed to give a meaningful result for a standard-layout type; on a type with virtual functions, virtual bases, multiple access specifiers, or non-trivial members, the call is conditionally-supported and its behavior is implementation-defined or undefined by both the C and C++ standards. It also silently breaks if the member it names is ever moved behind an access-specifier boundary or into a base class, with no compiler warning at the call site.
The following code illustrates the pattern detected by this rule:
struct Plain {
int a;
int b;
};
void f1(void) {
// FLAGGED: Use of the offsetof macro
size_t off = offsetof(struct Plain, b);
}