Skip to content

BUG: Use memcpy instead of casting to over-aligned pointer types - #116

Open
hjmjohnson wants to merge 1 commit into
masterfrom
pr/fix-cast-align-memcpy
Open

hjmjohnson wants to merge 1 commit into
masterfrom
pr/fix-cast-align-memcpy

Conversation

@hjmjohnson

Copy link
Copy Markdown
Member

Re-submission of #44, reverted from master on 2026-09-24 so it can be
reviewed before merging. Content is unchanged from the original.

Base: master. Independent: nothing has to land before it.

Commits
  • BUG: Use memcpy instead of casting to over-aligned pointer types

Ordering for all the re-submitted work is tracked in #84.

19 -Wcast-align warnings, and behind them undefined behavior on any
target that cares about alignment.

modify_field() writes a value into a header field at a byte offset
parsed from a field table:

    ((short *)((char *)basep + field->offset))[fc] = (short)val;

field->offset is a byte offset into a packed on-disk header, so that
cast produces an address only correctly aligned by coincidence.  The
same pattern appears for int, int64_t, float and double, in both tool
files.  Each becomes a memcpy of the right width at the right byte
offset.

The second group reads a pointer back out of a structure through a
byte offset -- `sp = *(char **)((char *)str + fp->offset)` and the
nifti1_extension equivalents -- and becomes a memcpy into an aligned
local.

The third is nifti_header_version(), which cast its `const char * buf`
argument, a buffer straight off a file read with no alignment
guarantee, to both nifti_1_header * and nifti_2_header * and read
fields through them.  It now copies into aligned locals first, exactly
the sizeof(nifti_1_header) bytes the function already checks are
present.

Verified by round-tripping int16, int32, int64, float32, float64 and
string fields through nifti_tool -mod_hdr2.

(cherry picked from commit eb4f831)
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

Successfully merging this pull request may close these issues.

3 participants