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

后端 未结 6 1410
臣服心动
臣服心动 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

    On top of what the other answers have said, this is a classic anti-pattern in C, and one which should be burned with fire. It appears in:

    1. Free-and-null-out functions like the one you've found the warning in.
    2. Allocation functions that shun the standard C idiom of returning void * (which doesn't suffer from this issue because it involves a value conversion instead of type punning), instead returning an error flag and storing the result via a pointer-to-pointer.

    For another example of (1), there was a longstanding infamous case in ffmpeg/libavcodec's av_free function. I believe it was eventually fixed with a macro or some other trick, but I'm not sure.

    For (2), both cudaMalloc and posix_memalign are examples.

    In neither case does the interface inherently require invalid usage, but it strongly encourages it, and admits correct usage only with an extra temporary object of type void * that defeats the purpose of the free-and-null-out functionality, and makes allocation awkward.

提交回复
热议问题