Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

loadUnaligned and strict aliasing #2150

Open
jj683 opened this issue Feb 23, 2024 · 0 comments
Open

loadUnaligned and strict aliasing #2150

jj683 opened this issue Feb 23, 2024 · 0 comments

Comments

@jj683
Copy link

jj683 commented Feb 23, 2024

Is folly::loadUnaligned function correct in terms of strict-aliasing rules?

A minimal example that reproduces undefined behavior:

#include <iostream>

#include <folly/Bits.h>

uint16_t checksum(uint8_t a, uint8_t b, uint64_t c, uint64_t d) {
  std::array<char, 2 + 8 + 8> buffer;
  folly::storeUnaligned<uint8_t>(buffer.data() + 0, a);
  folly::storeUnaligned<uint8_t>(buffer.data() + 1, b);
  folly::storeUnaligned<uint64_t>(buffer.data() + 2, c);
  folly::storeUnaligned<uint64_t>(buffer.data() + 2 + 8, d);

  uint16_t checksum = 0;
  for (std::size_t i = 0; i < buffer.size(); i += 2) {
    checksum += folly::loadUnaligned<uint16_t>(buffer.data() + i);
  }

  return checksum;
}

int main() {
  uint8_t a = 0, b = 0;
  uint64_t c = 0, d = 0;

  std::cout << checksum(a, b, c, d) << std::endl;

  return 0;
}

Compiler version: g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Compiler flags: g++ -std=c++17 -O2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant