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

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

    A void * is treated specially by the C standard in part because it references an incomplete type. This treatment does not extend to void ** as it does point to a complete type, specifically void *.

    The strict aliasing rules say you can't convert a pointer of one type to a pointer of another type and subsequently dereference that pointer because doing so means reinterpreting the bytes of one type as another. The only exception is when converting to a character type which allows you to read the representation of an object.

    You can get around this limitation by using a function-like macro instead of a function:

    #define freeFunc(obj) (free(obj), (obj) = NULL)
    

    Which you can call like this:

    freeFunc(f);
    

    This does have a limitation however, because the above macro will evaluate obj twice. If you're using GCC, this can be avoided with some extensions, specifically the typeof keyword and statement expressions:

    #define freeFunc(obj) ({ typeof (&(obj)) ptr = &(obj); free(*ptr); *ptr = NULL; })
    

提交回复
热议问题