Why is this claimed dereferencing type-punned pointer warning compiler-specific?

后端 未结 6 1411
臣服心动
臣服心动 2021-02-05 00:43

I\'ve read various posts on Stack Overflow RE: the derefercing type-punned pointer error. My understanding is that the error is essentially the compiler warning of the danger of

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 01:38

    Dereferencing a type punned pointer is UB and you can't count on what will happen.

    Different compilers generate different warnings, and for this purpose different versions of the same compiler can be considered as different compilers. This seems a better explanation for the variance you see than a dependence on the architecture.

    A case which may help you understand why type punning in this case can be bad is that your function won't work on an architecture for which sizeof(Foo*) != sizeof(void*). That is authorized by the standard although I don't know any current one for which this is true.

    A workaround would be to use a macro instead of a function.

    Note that free accepts null pointers.

提交回复
热议问题