The nullptr and pointer arithmetic

前端 未结 4 639
执念已碎
执念已碎 2021-02-05 21:23

Considering the following code, is it safe to do pointer arithmetic on nullptr?

I assume adding any offsets to a nullptr results in another

4条回答
  •  萌比男神i
    2021-02-05 22:05

    ... is it safe to do pointer arithmetic on nullptr?

    No, arithmetic on the nullptr is not well defined since it is itself not a pointer type (but conversions to NULL values of all pointer types exist).

    See here;

    std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type.


    In general, arbitrary pointer arithmetic (even on the NULL value) is almost certainly going to cause problems - you didn't allocate that memory - it is not yours to attempt to read or write to.

    For comparison purposes (e.g. one past the end), you will be fine, but otherwise the code you have will result in undefined behaviour.

    For further reading, see Wikipedia on undefined behavior.

提交回复
热议问题