`prevector` is basically doing UB if on C++17 #26427

issue cculianu opened this issue on October 31, 2022
  1. cculianu commented at 2:22 PM on October 31, 2022: none

    Things like this are technically UB in C++17: https://github.com/bitcoin/bitcoin/blob/4766cd198172225c66a0adb01f6cb9513c3d0e66/src/prevector.h#L187

    • You cannot start the lifetime of an array like this. You need to do some compiler magic (such as perhaps call std::launder? Or actually some weird placement-new that does nothing?) here to properly start the lifetime of the T array object, as far as the C++ abstract machine is concerned. See: https://www.youtube.com/watch?v=pbkQG09grFw
      • C++20 does now allows this -- implicit lifetimes can be started when you use some backing store in this way for trivial types only, but in C++17 this is technically UB.
      • The fact that this works is a happy accident because most major compiler support such (mis)-use of the language for trivial types owing to its C roots. So much so that they actually changed the standard for C++20 to support this, but for '17 this is UB (but works in practice on all major compilers).
    • The following is not fixed in C++20 though: Memory is not guaranteed to be aligned to whatever T requires here. (This is not fixed by C++20 -- unaligned access is UB, even if it happens to work on your platform). So prevector only really works without UB for uint8_t and similar types, if on C++20.
  2. cculianu added the label Bug on Oct 31, 2022
  3. cculianu closed this on Oct 31, 2022

  4. maflcko commented at 12:12 PM on November 14, 2022: member

    My guess would be that is already fixed in 07cb4dee5d12657e9cf33c442678e9a1cd2cec4a

  5. cculianu commented at 1:19 PM on November 14, 2022: none

    Yeah that should do it. I closed this because actually the C++ spec is confusing on this. I thought more was UB but yes it should be enough to check if trivial. And yes, removing that branch that does nothing is a good idea in https://github.com/bitcoin/bitcoin/commit/07cb4dee5d12657e9cf33c442678e9a1cd2cec4a

  6. bitcoin locked this on Nov 14, 2023
Contributors
Labels

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-05-01 00:13 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me