I have questions about typecasting. This is just a dummy program shown here. The actual code is too big to be posted.
typedef struct abc
{
int a;
}abc_t;
main()
{
abc_t *MY_str;
char *p;
MY_str = (abc_t *)p;
}
Whenever I run the quality analysis check tool, I get a level 2 warning:
Casting to different object pointer type. REFERENCE - ISO:C90-6.3.4 Cast Operators - Semantics <next> Msg(3:3305) Pointer cast to stricter alignment. <next>
Can anyone please tell me how to r开发者_如何学Goesolve this issue?
Simple - your static analysis tool (which, btw?) has decided that a char*
does not have a particular alignment requirement (it could point anywhere in memory) whereas an abc_t*
likely has a word alignment requirement (int
must be on a 4/8 byte boundary).
In reality, as the char*
is on the stack, it will be word aligned on most architectures. Your tool cannot see this.
In your implementation (and probably many others) each int
must be at an address that is divisible by sizeof int
, which is often 4.
On the other hand, a char
can be at any address.
It's like assigning 3.25
to an int
variable. That's also not possible.
So when you have a bad pointer, you will probably get an exception from your machine, and technically this code invokes undefined behavior.
a char*
can be aligned on any byte boundary, which means if you cast it to a structure, the alignment requirements of that struct might not be met (such as 16 byte boundaries required for SIMD types).
Your code is invalid C. If you find yourself doing something like this, it's probably the result of a greater misunderstanding. For instance I'm guessing you want to read an abc_t
object from a file/socket/etc. and you're used to passing a char
pointer to the read
/recv
/whatever function. Instead you should just declare an object of type abc_t
and pass its address to whatever reading function you're using.
精彩评论