Skip to content

Instantly share code, notes, and snippets.

@ahamez
Last active July 22, 2018 15:34
Show Gist options
  • Save ahamez/63ffa85a8b3ddd1def2e511a3728a44b to your computer and use it in GitHub Desktop.
Save ahamez/63ffa85a8b3ddd1def2e511a3728a44b to your computer and use it in GitHub Desktop.
Padding and undefined behavior
// When compiled (macOS, 64 bits) with g++-8 -O3 -std=c++14 ub.cc -Wall -Wextra:
// 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// Notice the '1' coming from nowhere :-)
// Note that clang++ produces:
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#include <cstdint>
#include <iostream>
struct padding_auto
{
std::uint32_t field0;
// padding added here by the compiler
std::uint64_t field1;
};
int main()
{
const auto f0 = padding_auto{0, 0};
const auto f1 = padding_auto{0, 0};
const auto ptr0 = reinterpret_cast<const char*>(&f0);
for (auto i = 0ul; i < sizeof(padding_auto); ++i)
{
std::cout << +ptr0[i] << ' ';
}
std::cout << '\n';
const auto ptr1 = reinterpret_cast<const char*>(&f1);
for (auto i = 0ul; i < sizeof(padding_auto); ++i)
{
std::cout << +ptr1[i] << ' ';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment