core: align AutoBuffer's local storage to at least 8 bytes

AutoBuffer<uchar> (and <char>, <int8_t>, ...) is routinely used as raw
storage for float/double/int64 data. The heap path (new _Tp[]) is at least
8-byte aligned everywhere, but the local array `buf` only had the alignment
of _Tp: on 64-bit targets it happened to land on an 8-byte offset after the
pointer and two size_t members, on 32-bit targets it was 4-byte aligned, and
the object itself could sit at any 4-byte address.

alignas(max(alignof(_Tp), 8)) on `buf` makes the guarantee explicit on every
platform (C++11; OpenCV 5 requires C++17). Reordering the members or adding
a size_t padding field would not help on 32-bit targets, where the object's
own alignment stays 4.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Vadim Pisarevsky
2026-11-01 13:01:07 +03:00
parent 784be814b2
commit 02c6f39c82

View File

@@ -183,8 +183,11 @@ protected:
size_t sz;
//! capacity - allocated element count (>= sz). Starts at fixed_size (the local buf), grows on demand.
size_t cap;
//! pre-allocated buffer. At least 1 element to confirm C++ standard requirements
_Tp buf[(fixed_size > 0) ? fixed_size : 1];
//! pre-allocated buffer. At least 1 element to confirm C++ standard requirements.
//! Aligned to at least 8 bytes whatever _Tp is, so that a byte buffer (AutoBuffer<uchar>)
//! can hold doubles/int64 even when the local storage is used; the heap path (new _Tp[])
//! is at least that aligned on every supported platform.
alignas(alignof(_Tp) > 8 ? alignof(_Tp) : 8) _Tp buf[(fixed_size > 0) ? fixed_size : 1];
};
/** @brief Sets/resets the break-on-error mode.