Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the standard say about unaligned memory access?

I've searched through the standard about unaligned access, but didn't find anything (maybe I was inadvertent).

Is it undefined behavior? Is it implementation defined?

As a lot of current CPUs support unaligned access, it would be sensible that unaligned memory access is implementation defined. Is it the case?

By unaligned access, I mean for example:

alignas(int) char buffer[sizeof(int)+1];
int &x = *new(buffer+1) int;
x = 42;
like image 730
geza Avatar asked Sep 07 '25 07:09

geza


1 Answers

No, it is UB. You cannot start the lifetime of an object at unaligned memory. From [basic.life]p1

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and

  • if the object has non-vacuous initialization, its initialization is complete,

[...]

So in your example, the lifetime of the object referenced by x doesn't even begin, so any other usage of it other than mentioned in [basic.life]p6 is UB.

But what your implementation is allowed to do is say that unaligned memory (as specified by the underlying architecture used) is actually aligned, thus making your code valid under the C++ abstract machine. I'm not sure whether any compiler does this however.

like image 152
Rakete1111 Avatar answered Sep 10 '25 08:09

Rakete1111