About generic pointer to char and strict aliasing

一笑奈何 提交于 2019-12-06 08:13:13

It is not allowed. The part of the Standard you posted shows through what types are you allowed to alias objects.

The fact that the code compiled doesn't mean it is correct. You are having three problems with the code that make it the program exhibit undefined behavior.

First is that you assigned a char pointer to an int pointer. Standard doesn't enforce their alignment and representation, so the resulting pointer is not valid.

int  *q = (int *)p;

Then you interpreted the char n object as an integer, violating strict aliasing.( Note the quote from the Standard in your question ).

*q;

Finally you wrote an int into the memory of the char object (char n), which causes an overflow because the size of an int is always larger than size of a char.

*q = 10;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!