I am running cppcheck (c++11) against a library that contains many casts similar to the below:
// Allocates various buffers
int* i_buffer = (int*) calloc (500, sizeof (int));
float* f_buffer = (float*) i_buffer;
For these casts, I see the following message:
"portability","invalidPointerCast","Casting between integer* and float* which have an incompatible binary data representation."
What is the correct way to perform the type of cast shown above ? What is the potential consequence of casting the pointer the way it is shown above ?
Strictly speaking the behaviour of your code is undefined due to a strict aliasing violation.
In practice, if int
and float
are the same size (they are on many desktop platforms although there is some push to move int
to 64 bit), then the code will run without error. Although to re-iterate, from the perspective of standard C++ there is absolutely no guarantee of this.
But you should still fix it. Allocating the float
array directly is the sensible thing to do:
float* f_buffer = (float*) calloc (500, sizeof (float));