Is apparent NULL pointer dereference in C actually pointer arithmetic?

后端 未结 5 1395
时光取名叫无心
时光取名叫无心 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

    Just to clarify that you must understand the difference between NULL-pointer dereference and when it's not considered a de-reference. The spec actually dictates that the de-reference does not happen, and is actually optimised away when you have the & (address-of) operator in the expression.

    So the &((struct T*)0)->b) actually optimises out the -> and just jumps that number of bytes from offset 0 and assumes it's a struct T *. This really obfuscates things for new beginners. However, it's widely used in the Linux Kernel - and provides an actual sense of list_entry, list_head's and various pointer arithmetic magic that newbies can't comprehend.

    In any event, it's a programmatic way of finding the offset of 'b' within the struct T object. It's used in offsetof as well as other list_head operations such as list_entry.

    For more information - you can read about this within Robert Love's Book titled "Linux Kernel Development".

提交回复
热议问题