Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time check to make sure that there is no padding anywhere in a struct

Is there a way to write a compile-time assertion that checks if some type has any padding in it?

For example:

struct This_Should_Succeed
{
    int a;
    int b;
    int c;
};

struct This_Should_Fail
{
    int a;
    char b;
    // because there are 3 bytes of padding here
    int c;
};
like image 501
Kalinovcic Avatar asked Sep 07 '19 00:09

Kalinovcic


People also ask

How do you prevent struct padding?

So, to avoid structure padding we can use pragma pack as well as an attribute.

How does padding work in a struct?

The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.

What is structure padding why is it required How do you avoid structure padding?

The structural padding is an in-built process that is automatically done by the compiler. Sometimes it required to avoid the structure padding in C as it makes the size of the structure greater than the size of the structure members. We can avoid the structure padding in C in two ways: Using #pragma pack(1) directive.

What is __ packed in C?

4.11 The __packed__ Attribute This attribute, attached to struct or union type definition, specifies that each member (other than zero-width bitfields) of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.


1 Answers

Since C++17 you might be able to use std::has_unique_object_representations.

#include <type_traits>

static_assert(std::has_unique_object_representations_v<This_Should_Succeed>); // succeeds
static_assert(std::has_unique_object_representations_v<This_Should_Fail>); // fails

Although, this might not do exactly what you want it to do. Check the linked cppreference page for details.

like image 136
Indiana Kernick Avatar answered Sep 18 '22 17:09

Indiana Kernick