Skip to content

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

Merged
hjmjohnson merged 1 commit into
InsightSoftwareConsortium:masterfrom
gdevenyi:pr/fix-cast-align-memcpy
Sep 22, 2026
Merged

hjmjohnson merged 1 commit into
InsightSoftwareConsortium:masterfrom
gdevenyi:pr/fix-cast-align-memcpy

Conversation

@gdevenyi

@gdevenyi gdevenyi commented Aug 15, 2026 •

Copy link
Copy Markdown

19 -Wcast-align warnings, and behind them undefined behaviour 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. This
is the fix attempted in NIFTI-Imaging#172, which was never
merged and still carries assert(0) and "// TEMP" scaffolding; it is
re-derived here cleanly.

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.


Interface impact: none. On the union of all these changes, configured with USE_FSL_CODE=ON and USE_CIFTI_CODE=ON: all 448 exported symbols across libniftiio, libnifti2, libznz, libfslio, libnifticdf and libcifti are identical to master under nm -D --defined-only, and all ten installed headers are identical under gcc -E -P. Under gcc -dM -E one macro definition differs, intentionally and only in text: #61 makes FSL_RADIOLOGICAL read (-1) so it is safe inside an expression. Its value is still -1, checked by compiling against each installed fslio.h and printing it.

Verification. This branch: builds with gcc 16.1.1, ctest unchanged from master (2 of 345 fail on master itself in this environment; #31 and #29 each fix one). The union of all the PRs: 0 errors under both gcc 16.1.1 and clang 22.1.8, ctest 345/345 under each, and the whole suite under valgrind memcheck with --trace-children=yes gives 484 traced processes with no invalid access, no uninitialised value and no leak in any nifti binary.

Coordination. Every line of every branch was compared, whitespace-normalised, against the diffs of the open PRs (#11, #21, #22, #23, #24). Where one of those already changes a line, the line was left alone, and the few deliberate overlaps are named in the text above. What survives is 17 compiler warnings, all of them on those lines: 9 -Wsign-conversion (5 in fslio.c for #22, 2 in nifti2_io.c and 2 in nifti_tester001.c for #24) and 8 -Wcalloc-transposed-args in nifti_findhdrname and nifti_findimgname, which #11 rewrites. No formatting changes appear anywhere, to stay clear of #10 and #12.

One of a set of independent, single-purpose PRs. Each bases on master and can be merged on its own, in any order.

The full set of PRs (35)

The union of all of them is on the fork as all-changes, if you want to build and test the lot at once.

CI and build

Configuration and documentation

Defects

Warning and check classes

This was referenced Aug 15, 2026
@hjmjohnson

Copy link
Copy Markdown
Member

Rebased onto master (b4876bf) and cleaned the commit message. No code change from the reviewed version.

No regression test applies — the UB is latent, not reachable in tree. Details below.

Message cleanup

Removed the Co-Authored-By: trailer naming an AI tool and the Claude-Session: URL; changed "behaviour" to "behavior" (US English); rewrapped the body to 72 columns. Author and author date preserved (Gabriel A. Devenyi, 2026-08-14).

Also dropped the paragraph referring to the unmerged upstream attempt; that relationship belongs in the PR description rather than in permanent history.

Why there is no red-green test (NOT-DEMONSTRABLE)

Unaligned access is real UB but invisible on x86-64 and arm64, so the only observer is UndefinedBehaviorSanitizer. I built the tree without this fix at -fsanitize=alignment -fno-sanitize-recover=alignment:

cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_C_FLAGS="-fsanitize=alignment -fno-sanitize-recover=alignment -g" \
  -DCMAKE_EXE_LINKER_FLAGS=-fsanitize=alignment \
  -DNIFTI_BUILD_APPLICATIONS=ON -DUSE_NIFTI2_CODE=ON -DUSE_CIFTI_CODE=ON -DUSE_FSL_CODE=ON

100% tests passed, 0 tests failed out of 362

No test trips. The reason is structural, not a gap in coverage:

  • In modify_field() the address is basep + field->offset. basep is always a malloced or stack nifti_1_header / nifti_2_header, and every scalar field in both headers sits at its own natural offset within that struct. So the cast, while ill-typed, lands on a correctly aligned address on every in-tree path.
  • nifti_header_version() is the one function taking a caller-supplied const char *, and both in-tree callers (nifti2_io.c:5851, :6004) pass (char *)&n1hdr — an aligned local.

A test could only fail by deliberately handing nifti_header_version() a buf + 1, which no caller does and which would be asserting against a synthetic scenario rather than a real one. Reporting NOT-DEMONSTRABLE rather than manufacturing that.

The fix still stands on its own: it removes 19 -Wcast-align warnings and makes the code correct by construction for any external caller or any future in-tree caller that does not happen to pass an aligned buffer.

Build and test

Release, NIFTI_BUILD_APPLICATIONS=ON USE_NIFTI2_CODE=ON USE_CIFTI_CODE=ON USE_FSL_CODE=ON: 100% tests passed, 0 tests failed out of 362.

Same 362 pass with the fix applied under -fsanitize=alignment -fno-sanitize-recover=alignment.

Whitespace churn check: git diff -w master HEAD and git diff master HEAD both report 44 added lines — no reformatting.

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.
@hjmjohnson
hjmjohnson force-pushed the pr/fix-cast-align-memcpy branch from 956dccd to 81c2953 Compare September 22, 2026 15:53
@hjmjohnson
hjmjohnson merged commit eb4f831 into InsightSoftwareConsortium:master Sep 22, 2026
25 checks passed
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.

2 participants