Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
Aviv Cohn Avatar asked Sep 08 '20 15:09

Aviv Cohn


1 Answers

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.

like image 69
eerorika Avatar answered Oct 06 '22 00:10

eerorika