Is apparent NULL pointer dereference in C actually pointer arithmetic?

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

    You must be using a 32-bit compile (or a 64-bit compile on Windows).

    The first expression - for num - is a common implementation of the offsetof macro from ; it is not portable, but it often works.

    The second expression adds that to 0 (the null pointer) and gives you the same answer - 4. The second expression adds 4 to the base address of the object that ptr points to, and that is the value 4 in the structure.

    Your output does not include a newline - it probably should (the behaviour is not completely portable because it is implementation defined if you don't include the newline: C99 §7.19.2: "Whether the last line requires a terminating new-line character is implementation-defined."). On a Unix box, it is messy because the next prompt will appear immediately after the 44.

提交回复
热议问题