Main Content

MISRA C++:2023 Rule 21.2.4

The macro offsetof shall not be used

Since R2024b

Description

Rule Definition

The macro offsetof shall not be used.

Rationale

Using offsetof exposes the memory layout of a class or structure and breaks its encapsulation. Additionally, use of the offsetof macro can result in undefined behavior if the specified member is a bit-field, static data member, or member function.

Design your classes to avoid the need for offsetof. For example, you can use member functions or operator overloading to access members indirectly. If you need to work with offsets, consider using member function pointers or designing your class to provide the necessary access in a type-safe manner.

Polyspace Implementation

The rule checker reports a violation for any use of the offsetof macro.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <iostream>
#include <cstddef>

struct SimpleStruct {
    int a;
    float b;
};

int main() {
    SimpleStruct s{10, 3.14f};

    size_t offset_b = offsetof(SimpleStruct, b);		//Noncompliant

    float* ptr_b = reinterpret_cast<float*>(reinterpret_cast<char*>(&s) + offset_b);

    std::cout << "Value of b: " << *ptr_b << std::endl;
    *ptr_b = 6.28f;
    std::cout << "Updated value of b: " << s.b << std::endl;

    return 0;
}

In this example, the code uses offsetof to obtain the offset of the member b within the structure SimpleStruct.

To avoid the use of offsetof, you can instead directly take the address of the member b and use a pointer to access and modify its value.

#include <iostream>

struct SimpleStruct {
    int a;
    float b;
};

int main() {
    SimpleStruct s{10, 3.14f};

    // Directly getting the address of member b
    float* ptr_b = &s.b;                            //Compliant

    std::cout << "Value of b: " << *ptr_b << std::endl;
    // Modify the value of b using the pointer
    *ptr_b = 6.28f;                        
    std::cout << "Updated value of b: " << s.b << std::endl;

    return 0;
}

Check Information

Group: Language support library
Category: Required

Version History

Introduced in R2024b