Is incrementing a null pointer well-defined?

后端 未结 9 477
情话喂你
情话喂你 2020-12-03 04:17

There are lots of examples of undefined/unspecified behavior when doing pointer arithmetics - pointers have to point inside the same array (or one past the end), or inside t

9条回答
  •  甜味超标
    2020-12-03 04:41

    Operations on a pointer (like incrementing, adding, etc) are generally only valid if both the initial value of the pointer and the result point to elements of the same array (or to one past the last element). Otherwise the result is undefined. There are various clauses in the standard for the various operators saying this, including for incrementing and adding.

    (There are a couple of exceptions like adding zero to NULL or subtracting zero from NULL being valid, but that doesn't apply here).

    A NULL pointer does not point at anything, so incrementing it gives undefined behaviour (the "otherwise" clause applies).

提交回复
热议问题