Skip to content

Fix HeapMeta alignment on 32-bit platforms using C11 union#451

Open
mstorm wants to merge 1 commit intofacebook:devfrom
kwonlabs:fix/allocation-alignment-32bit
Open

Fix HeapMeta alignment on 32-bit platforms using C11 union#451
mstorm wants to merge 1 commit intofacebook:devfrom
kwonlabs:fix/allocation-alignment-32bit

Conversation

@mstorm
Copy link

@mstorm mstorm commented Mar 2, 2026

Summary

This PR addresses alignment issues for HeapMeta on 32-bit architectures by restructuring it using a C11 anonymous struct within a union. This enforces a 16-byte size without altering its alignof requirement, preventing potential alignment-related crashes on 32-bit systems (where malloc typically returns 8-byte aligned addresses).

Fixes #342

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Test Plan

  • Ran make lib to verify that the static assertion sizeof(HeapMeta) == 16 passes across different configurations.
  • Ran make test (1619 tests passed) to ensure no regressions in allocator logic and overall functionality.
  • Verified memory layout and assembly code generation (ARM64, -O2) to confirm zero runtime overhead.

Test Configuration

  • Compiler: Apple clang version 17.0.0
  • Build type: Default (Release)
  • Platform(s): macOS (Apple Silicon / arm64), logic verified for ILP32 (32-bit arm/x86) compatibility.

Technical Analysis (For Reviewers)

We compared three approaches: (1) Manual #ifdef padding, (2) ZL_ALIGNED(16), and (3) C11 union.

  • Efficiency: Assembly analysis shows that the union approach generates identical machine code to the original struct. Field access (stp/ldp) and pointer arithmetic remain optimal.
  • Safety: Unlike ZL_ALIGNED(16), which raises alignof(HeapMeta) to 16 and could cause runtime assertion failures with 8-byte aligned malloc pointers, the union approach keeps the original alignment requirement (8) while guaranteeing the 16-byte size.
  • Portability: Uses standard C11 features, avoiding non-standard attributes or platform-specific macros.
Metric Original Struct C11 Union
sizeof 16 (64-bit) / 8 (32-bit) 16 (Both)
alignof 8 8
Codegen Baseline Identical

@meta-cla meta-cla bot added the cla signed label Mar 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

support for 32-bit devices

1 participant