Is apparent NULL pointer dereference in C actually pointer arithmetic?

后端 未结 5 1402
时光取名叫无心
时光取名叫无心 2020-12-18 05:37

I\'ve got this piece of code. It appears to dereference a null pointer here, but then bitwise-ANDs the result with unsigned int. I really don\'t understand the

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 05:59

    This gives you the offset in bytes of the b field inside the hi struct

    ((struct hi *)0) is a pointer to a hi struct, starting at address 0.

    (((struct hi *)0)->b) is the b field of the above struct

    & (((struct hi *)0)->b) is the address of the above field. Because the hi struct is located at address 0, this is the offset of b within the struct.

    (unsigned int) & (((struct hi *)0)->b) is a conversion of that from the address type to unsigned int, so that it can be used as a number.

    You're not actually dereferencing a NULL pointer. You're just doing pointer arithmetic.


    Accessing (((struct hi *)0)->b) will give you a segmentation fault because you're trying to access a forbidden memory location.

    Using & (((struct hi *)0)->b) does not give you segmentation fault because you're only taking the address of that forbidden memory location, but you're not trying to access said location.

提交回复
热议问题