The nullptr and pointer arithmetic

亡梦爱人 提交于 2019-12-04 20:17:27

问题


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

I assume adding any offsets to a nullptr results in another nullptr, so far MSVC produce results as I expected, however I am a bit unsure about whether using nullptr like this is safe:

float * x = nullptr;

float * y = x + 31; // I assume y is a nullptr after this assigment

if (y != nullptr)
{
  /* do something */
}

回答1:


You didn't define what "safe" means to you, but regardless, the code you propose has undefined behaviour. Pointer arithmetic is only allowed on pointer values that point into an array object, or perhaps to one-past-the-end of an array. (Non-array objects are considered an array of one element for the purpose of this rule.)

Since the null pointer is never the address of an object or one past an object, your code can never have well-defined behaviour.




回答2:


is it safe to do pointer arithmetic on nullptr? 

C++ defines two kind of operations on nullptr. For :

float * x=nullptr;
float * y=nullptr;
  1. x +/- 0 = x

  2. x-y=0 //note x and y have the same type

You cannot make an assumption about what is not defined, so you shouldn't do it.




回答3:


... 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.




回答4:


No, adding an offset to a nullptr does not result in a nullptr. This is undefined behavior.



来源:https://stackoverflow.com/questions/38526510/the-nullptr-and-pointer-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!