Aviv Cohn
Aviv Cohn

Reputation: 17193

Does reinterpret_cast with uint8_t break the Strict Aliasing Rule?

Is the following code legal in terms of the Strict Aliasing Rule (and in general)?

const int size = 1024;
uint8_t* buffer = allocateBuffer(size);
float* float_pointer = reinterpret_cast<float*>(buffer);
std::fill(float_pointer, float_pointer + size / sizeof(float), 1.5f);

As far as I understand, generally speaking SAR says we cannot access (either read or write) data through a pointer of a different type - unless we use a pointer of character type.

However, in the above code we use a pointer of a non-character type (float*) to read or write data of (probably) a character type (uint8_t), which I think is illegal.

Am I correct?

Upvotes: 5

Views: 272

Answers (1)

eerorika
eerorika

Reputation: 238341

However, in the above code we use a pointer of a non-character type (float*) to read or write data of (probably) a character type (uint8_t), which I think is illegal.

Am I correct?

Yes.

Is the following code legal in terms of the Strict Aliasing Rule (and in general)?

No.


Besides pointer aliasing, another consideration is that alignment requirement of float is stricter than that of uint8_t. There is doubt whether uint8_t* allocateBuffer(arg) returns a pointer that satisfies the alignment of float.

Upvotes: 5

Related Questions