array_t::at() returns a misaligned reference when the stride is not a multiple of alignof(T)

Offen
#6,309 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 3 Tagen

@henryiii arbeitet bereits daran.

Seit 25.11.2026.

  • #6311 von @henryiii — offen

Bewertung

Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Anfängerfreundlichkeit
35/100
Issue-Typ
Bug
Klarheit
Größtenteils klar
Aktivitätsstatus
Aktiv
Tech-Stack
cpp, python
Bereich
api, data

Rechercherichtung

The misaligned reference comes from array_t::at() and mutable_at() in include/pybind11/numpy.h, around line 1526. Start with the element address calculation there, then run test_at_stride_not_multiple_of_itemsize under the UBSan CI job, which currently deselects it. Done means the test passes under UBSan without the deselect, and either a throw for misaligned elements or an alignment check at array creation has been chosen and implemented.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

🤖 AI text below 🤖

Since #6241, array_t<T>::at() and mutable_at() support strides that are not a multiple of sizeof(T). They return a T & to the element. If the stride is not a multiple of alignof(T), that reference is misaligned. This is undefined behavior. It works on x86 and arm64, but it can fail on platforms that require aligned access, and UBSan reports it:

include/pybind11/numpy.h:1526: runtime error: reference binding to misaligned address 0x00000a5cf433 for type 'const short unsigned int', which requires 2 byte alignment

Reproducer (from test_at_stride_not_multiple_of_itemsize):

packed = np.zeros(3, dtype=[("a", np.uint16), ("b", np.uint8)])
m.at_t(packed["a"], 1)  # stride 3, element 1 is at an odd address

A reference cannot point to a misaligned T. Possible fixes:

  • Throw when the element address is not aligned for T.
  • Throw when the array is not aligned (NPY_ARRAY_ALIGNED), possibly as a check when the array_t is created.

The UBSan CI job deselects this test until this is fixed.

Vorherrschende Sprache
C++
Sterne
18k
Forks
2.3k
Ø Merge
5 T. 7 Std.
Gemergte PRs (30 T.)
53

Entwicklungsumgebung

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus pybind/pybind11

Alle Issues in pybind/pybind11

Ähnliche Issues

Weitere Issues zu C++

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.