Questions tagged [strict-aliasing]

Strict aliasing is an assumption, made by the C or C++ compiler, that de-referencing pointers to objects of different types will never refer to the same memory location (i.e. they will not alias each other).

strict-aliasing
Filter by
Sorted by
Tagged with
17 votes
2 answers
3k views

Understanding restrict qualifier by examples

The restrict keyword's behavior is defined in C99 by 6.7.3.1: Let D be a declaration of an ordinary identifier that provides a means of designating an object P as a restrict-qualified pointer to ...
4 votes
1 answer
160 views

In C++ can you use one empty type as storage for another?

In C++, with reference to the standard, is it safe to use placement new to obtain a pointer to a struct with no members, using another struct with no members as storage? Something like the following: ...
2 votes
2 answers
116 views

How to workaround strict aliasing in C?

My aim is to make an generic arena allocator with an buffer stored in the .bss section of the executable to avoid any allocations in the actual program, however this has problems in C with strict ...
50 votes
3 answers
6k views

Why does optimisation kill this function?

We recently had a lecture in university about programming specials in several languages. The lecturer wrote down the following function: inline u64 Swap_64(u64 x) { u64 tmp; (*(u32*)&tmp)...
991 votes
11 answers
300k views

What is the strict aliasing rule?

When asking about common undefined behavior in C, people sometimes refer to the strict aliasing rule. What are they talking about?
3 votes
3 answers
174 views

Is accessing a struct within a struct by pointers undefined behavior?

I have a struct A that contains a struct B and I access A via a pointer pa and b via pointer ba. Is this undefined behavior (Strict Aliasing Rule)? (The struct B part is not accessed by the pointer to ...
4 votes
1 answer
151 views

Do we have a Strict Aliasing rule violation?

Do we have a Strict Aliasing rule violation in this code? I thought that int -> char and int -> std::byte are OK, but what about int8_t? int main() { int arr[8] = {1, 1, 1, 1, 1, 1, 1, 1}; //...
0 votes
3 answers
141 views

Aliasing rules and making Rust function "generic over aliasing"

I have a routine which takes in an immutable slice of points and performs some transformation, writing to a mutable slice of points. (As a simple example, let's say we translate all the points by some ...
5 votes
3 answers
199 views

Does casting a char * to another pointer type break the strict aliasing rule when the memory is from malloc?

I read that char *- and their signed and unsigned counterparts - can alias any type without violating the strict aliasing rule. However, having a char * point to an int variable and casting that char *...
9 votes
2 answers
987 views

Implementation of std::start_lifetime_as()

After P0593R6 ('Implicit creation of objects for low-level object manipulation') was accepted in C++20, C++23 will get std::start_lifetime_as() which 'completes the functionality proposed in [P0593R6]'...
3 votes
2 answers
128 views

How do initial members, common initial sequences, anonymous unions, and strict aliasing interact in C?

So there are several things that are clearly allowed under the strict aliasing rules (for clarity, lets do this in C23): The first and most obvious is that structs are allowed to alias with pointers ...
0 votes
1 answer
101 views

When does std::as_writable_bytes trigger undefined behavior

I thought I finally understood reinterpret_cast and strict aliasing, and then I came across this example, slightly modified from the "Invalid scalar" example on https://en.cppreference.com/w/...
1 vote
3 answers
229 views

Placement new + reinterpret_cast in C++14: well-formed?

Consider the following example in C++14: alignas(T) unsigned char data[sizeof(T)]; new (data) T(); T* p = reinterpret_cast<T*>(data); p->something(); // UB? Is this code legal, or are the ...
31 votes
8 answers
11k views

What's a proper way of type-punning a float to an int and vice-versa?

The code below performs a fast inverse square root operation by some bit hacks. The algorithm was probably developed by Silicon Graphics in early 1990's and it's appeared in Quake 3 too. more info ...
5 votes
0 answers
143 views

Opt out of `char` exemption to strict aliasing rules [duplicate]

If I have a simple piece of code using uint32_t then it can be optimised better than the same code with uint8_t. As far as I know this is because char has exemptions to the strict aliasing rules. ...
4 votes
1 answer
152 views

Standard compliant way of swapping bits of two objects in different types

Consider the following two functions: template<typename T, typename S> void swap1(T* t, S* s) { static_assert(sizeof(T) == sizeof(S)); char tmp[sizeof(T)]; std::memcpy(tmp, t, sizeof(T)); ...
31 votes
1 answer
2k views

Does a pointer to std::byte have the same aliasing relaxations as char*?

C++ (and C) strict aliasing rules include that a char* and unsigned char* may alias any other pointer. AFAIK there is no analogous rule for uint8_t*. Thus my question: What are the aliasing rules ...
2 votes
3 answers
174 views

Is it undefined behavior to access the object representation of a pointer through a char*?

I know this is weird question, but just bad curious. char* ptr = 0; strcpy( (char*) &ptr, "UB?"); This code means 'I will use the memory of ptr as a char array.' I think 'it's ...
28 votes
4 answers
9k views

Why can a char* alias with any object pointer, but not the other way around?

The accepted answer to What is the strict aliasing rule? mentions that you can use char * to alias another type but not the other way. It doesn't make sense to me — if we have two pointers, one of ...
3 votes
1 answer
138 views

Adversarial test against template generic STL vector pool

I have been coding C++ for many years. Most of my apps are built for solving problems in computational science/statistics/machine learning, so I have been extensively dealing with std::vectors storing ...
5 votes
1 answer
621 views

Is casting strings from `wchar_t` to `char16_t` legal if encoding and width is the same?

On Windows, wchar_t is a UTF-16(LE) formatted character, which is -- for the most part -- equivalent to char16_t. However, these two character types are still distinct types in the C++ type-system -- ...
8 votes
1 answer
527 views

Why do I get a strict-aliasing warning when using C-style arrays, but now when using std::array?

When compiling the following code with gcc 4.7 (g++-mp-4.7 (GCC) 4.7.0 built with MacPorts on OS X) I get seemingly contradictory results. The compiler does not complain when I try to reinterpret and ...
25 votes
5 answers
2k views

How can you repurpose an array of floats as an array of doubles without undefined behavior?

In one particular C++ function, I happen to have a pointer to a big buffer of floats that I want to temporarily use to store half the number of doubles. Is there a method to use this buffer as scratch ...
15 votes
3 answers
700 views

Can you alias an array of T through a struct of T, similar to how std::complex<T>[N] can alias T[N * 2]? [duplicate]

Since C++11 std::complex<T>[n] is guaranteed to be aliasable as T[n*2], with well defined values. Which is exactly what one would expect for any mainstream architecture. Is this guarantee ...
2 votes
1 answer
114 views

Is the author's cast-based implementation of an optional<bool> well-defined in P2641?

In P2641r4: Checking if a union alternative is active, the author provides an implementation of an optional<bool> as a motivating example and claims that this is well-formed. struct OptBool { ...
0 votes
0 answers
110 views

Do reinterpret_cast double* to unsigned long long* constitue a strict aliasing violation? [duplicate]

To give some context, I'm focusing the case of data serialization/deserialization without being dependent of the platform endianness. For integral types, we can use the bitwise-shifting operators for ...
1 vote
2 answers
166 views

Correctly using type-punning and erasure for array of objects

My goal is to have a memory pool non-template class that is used to store arrays of objects. The same memory pool object must be reusable for a different array (difference size, different type and/or ...
14 votes
1 answer
478 views

Why do compilers miss vectorization here?

Consider the following valarray-like class: #include <stdlib.h> struct va { void add1(const va& other); void add2(const va& other); size_t* data; size_t size; }; void ...
4 votes
0 answers
92 views

upcast and strict aliasing rule from C++20 [duplicate]

As per C++17 standard, §6.10 item 8: 8 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: (8.1) — the ...
0 votes
0 answers
67 views

casting between 2 layout compatible types

I'm a quite confused about whether or not it's possible to cast an object of a certain type to another type with the same layout. I am aware that supposedly similar questions have been posted on Stack ...
2 votes
1 answer
329 views

How to safely break the strict aliasing rule?

The following example is known to break the strict aliasing rule and therefore produce different results with and without optimization: int foo( float *f, int *i ) { *i = 1; *f ...
0 votes
0 answers
161 views

type-punning and strict aliasing rule for array of objects

There is already a lot of posts about strict aliasing rule and type-punning but I couldn't find an explanation that I could understand regarding array of objects. My goal is to have a memory pool non-...
10 votes
1 answer
189 views

On the term "(strict) aliasing violation" relating to class member access

This question refers to the current C++20 draft. The quoted passages have been slightly modified from previous standard iterations, but not in relevant ways as far as I know. I am looking for ...
5 votes
2 answers
202 views

Is it possible to backport std::byte to C++14

std::byte is defined in C++17 as: enum class byte : unsigned char {}; I'm currently stuck at using C++14, and I wonder if I add the same definition in C++14 (in some non-std namespace, along with the ...
5 votes
1 answer
153 views

Placing a structure into memory smaller than it

I'm optimizing a compression algorithm, which uses a structure that spans 2 bytes. But there are times when I'd like it to interpret just 1 byte, as its members that (I expect) to map onto the 2nd ...
2 votes
1 answer
223 views

C++ strict aliasing and UB

I'm reviewing some code (can't post all of it), but there's a function like this: template <typename DestType, typename SourceType> inline void transferDataAndUpdateSpan(MyArray<DestType>&...
0 votes
1 answer
65 views

reinterpret cast of a class template instantiation to another

I implemented a container template class owning a storage of type std::unique_ptr with customizable deleter, as follows: template <class D> struct Container { Container(const char* str) ...
0 votes
0 answers
171 views

How bad is memory aliasing with modern C++ compilers?

I am trying to understand the effects of memory aliasing and how to improve my code to avoid it. I am re-writing my cache coherent Entity Component System and I want to take memory aliasing into ...
-2 votes
3 answers
138 views

Is having a buffer of unsigned char and treating it as a pointer to T* a violation of strict aliasing?

Some sources say the following is a violation of strict aliasing: #include <stdlib.h> typedef struct Foo { int a; double* b; } Foo; int main() { _Alignas(Foo) unsigned char buffer[...
0 votes
2 answers
131 views

What does "*(Vector2*)&x"; in C++ mean?

I'm currently watching this tutorial on unions in C++, and here is a snippet of code provided by the Youtuber: #include <iostream> struct Vector2 { float x, y; }; struct Vector4 { ...
63 votes
6 answers
36k views

gcc, strict-aliasing, and horror stories [closed]

In gcc-strict-aliasing-and-casting-through-a-union I asked whether anyone had encountered problems with union punning through pointers. So far, the answer seems to be No. This question is broader: ...
0 votes
1 answer
148 views

How does C++ strict aliasing work with arrays and dynamically allocated memory?

I could not find a lot of resources like this that cover all of the edge cases of the strict aliasing rule. If I understand correctly, in C++ it is UB to access an object that does not exist at a ...
24 votes
3 answers
2k views

Examples using reinterpret_cast that do not trigger UB

Reading https://en.cppreference.com/w/cpp/language/reinterpret_cast I wonder what are use-cases of reinterpret_cast that are not UB and are used in practice? The above description contains many cases ...
0 votes
0 answers
89 views

C++ convert enum pointer to another enum class pointer

Let's say I have the following code template <class T> struct ArrayRef { ArrayRef(const T *, size_t count); }; enum class EImpl { In, Out }; enum ECApi { IN, OUT }; static_assert(ECApi::IN == ...
2 votes
4 answers
447 views

Is strict aliasing still something to think about in C?

I recently read a well-known article by Mike Acton about strict aliasing and how we should use it to increase performance significantly in C code. It seems to be simple, in some cases, that if you ...
1 vote
3 answers
106 views

Do FreeRTOS heap implementations violate C aliasing rules?

Looking at the code for heap 1 in FreeRTOS... #if ( configAPPLICATION_ALLOCATED_HEAP == 1 ) /* The application writer has already defined the array used for the RTOS * heap - probably so it can be ...
7 votes
1 answer
857 views

std::atomic in a union with another character

I recently read some code that had an atomic and a character in the same union. Something like this union U { std::atomic<char> atomic; char character; }; I am not entirely sure of ...
2 votes
3 answers
222 views

Inheritance and method overriding in C - how to make it defined behaviour

I have my custom little OOP-esque inheritance functionality, something like this: // base class struct BaseTag; typedef struct { int (*DoAwesomeStuff)(struct BaseTag* pInstance); } S_BaseVtable; ...
2 votes
2 answers
159 views

Are void** and int** compatible types?

To my understanding, void ** is not compatible with int **. I expect the code below to emit a warning for a violation of the strict aliasing rule, on the line where ptrs is cast to void ** and ...
0 votes
2 answers
94 views

Strict aliasing rule with incompatible but same structs

Does this code violate strict aliasing rule? Why or why not? #include <stdlib.h> #define STRUCT struct {int x; char y;} typedef STRUCT my_struct_t; void get(my_struct_t *data, int *x, char *y) ...

1
2 3 4 5
12