user2953119
user2953119

Reputation:

C++ pointer's suitable alignment

[basic.stc.dynamic.allocation]/2 about allocation functions:

The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement (3.11) and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).

It is a bit inclear. I thought that any pointer to (include the void*) type has alignment equal to 8. What is the point of The pointer returned shall be suitably aligned so...? Could you get an example of no suitable aligned pointer?

Upvotes: 0

Views: 389

Answers (1)

Mike Precup
Mike Precup

Reputation: 4218

Many systems require the dereferenced pointers are aligned to be a multiple of the size of the type. For instance, pointers for shorts would be on multiples of 2 bytes, char pointers are unrestricted, etc. Not all systems have this requirement, but accesses on unaligned memory on these systems are frequently very slow, and so typically programmers try to keep everything aligned anyways.

You can find the alignment requirement for a type with alignof, if you want to poke around on your system. A pointer that isn't aligned properly for any type might be something like 0xFFFF0002, which wouldn't be aligned for any 4 byte or higher type.

In short, what that documentation is saying is that the memory returned will be aligned for any fundemental type.

Upvotes: 2

Related Questions