Suppose I want to dynamically allocate space for an int
and write the maximum representable value into that memory. This code comes to mind:
auto rawMem = std::malloc(sizeof(int)); // rawMem's type is void*
*(reinterpret_cast<int*>(rawMem)) = INT_MAX; // INT_MAX from <limits.h>
Does this code violate C++'s rules about strict aliasing? Neither g++ nor clang++ complain with -Wall -pedantic
.
If the code doesn't violate strict aliasing, why not? std::malloc
returns void*
, so while I don't know what the static and dynamic types of the memory returned by std::malloc
are, there's no reason to think either is int
. And we're not accessing the memory as a char
or unsigned char
.
I'd like to think the code is kosher, but if it is, I'd like to know why.
As long as I'm in the neighborhood, I'd also like to know the static and dynamic types of the memory returned by the memory allocation functions (std::malloc
and std::operator new
).