When is an integer<->pointer cast actually correct?

后端 未结 15 2642
北荒
北荒 2020-12-13 07:48

The common folklore says that:

  • The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the m

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 08:35

    It could be useful when checking the alignment of types in general so that misaligned memory gets caught with an assert rather than just SIGBUS/SIGSEGV.

    E.g.:

    #include 
    #include 
    #include 
    
    int main() {
      void *ptr = malloc(sizeof(__m128));
      assert(!((intptr_t)ptr) % __alignof__(__m128));
      return 0;
    }
    

    (In real code I wouldn't just gamble on malloc, but it illustrates the point)

提交回复
热议问题