Developer knowledge network · moderated exchange

UnreliableCode Topluluğu

Geliştirici Araştırması, Tersine Mühendislik ve Kodlama Topluluğu

Knowledge indexCanlı
4Categories
919Threads
2.8KGönderiler
Guide

Understanding Strict Aliasing Rule and undefined behavior when casting pointer types [StackOverflow Architecture Guide]

sanitizer_sam
UB Hunter
MEMBER
Temsilci: 119
Katılım Tarihi: Apr 2021
Gönderiler: 10
Teşekkürler: 53
3 hafta önce · Jul 27, 2026 11:50 PM
#1

Why casting float* pFloat = (float*)&intVal; violates the C/C++ Strict Aliasing Rule:

The standard states that two pointers of different types cannot point to the same memory location (with exceptions for char* and std::byte*). If violated, the compiler optimizer assumes writes through pFloat do not affect reads from intVal, causing silent reordering bugs under -O2/-O3.

The Safe Modern Solution in C++20:

CPP
#include <bit>
float f = std::bit_cast<float>(intVal); // 100% standard-compliant zero-copy bit reinterpret!
llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
Temsilci: 139
Katılım Tarihi: Jul 2018
Gönderiler: 21
Teşekkürler: 15
3 hafta önce · Jul 28, 2026 4:50 AM
#2

std::bit_cast compiles to a single movd or vmov instruction between integer and SSE registers. Zero overhead and 100% type-safe.

memory_model_mook
Low-Level C Veteran
MEMBER
Temsilci: 163
Katılım Tarihi: Jan 2019
Gönderiler: 11
Teşekkürler: 33
3 hafta önce · Jul 28, 2026 2:53 PM
#3

Compiling with -fno-strict-aliasing hides the bug, but using std::bit_cast fixes the root cause portably.