Nullptr and pointer arithmetic

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

I am assuming adding any offsets to the nullptr result in another nullptr until MSVC produces the results as I expected, however I'm a little unsure that using nullptr as it is safe:

 float * x = nullptr; float * y = x + 31; // I assume y is a nullptr after this assigment if (y != nullptr) { /* do something */ } 
+5
source share
4 answers

You have not determined what is β€œsafe” for you, but no matter what code you offer, it has undefined behavior. Arithmetic of a pointer is allowed only by pointer values ​​that point to an array object or possibly to one end of the end of the array. (Objects without an array are considered an array of one element for the purpose of this rule.)

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

+11
source
 is it safe to do pointer arithmetic on nullptr? 

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

 float * x=nullptr; float * y=nullptr; 
  • x +/- 0 = x

  • xy=0 //note x and y have the same type

You cannot make an assumption about what is undefined, so you should not do this.

+3
source

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

No, arithmetic on nullptr not defined correctly, since it itself is not a pointer type (but there are transformations with NULL values ​​of all pointer types).

See here ;

std::nullptr_t - null pointer literal type, nullptr . This is a separate type, which in itself is not a pointer type or a pointer to a member type.


In general, arbitrary pointer arithmetic (even to a NULL value) will almost certainly cause problems - you have not allocated this memory - you do not need to try to read or write.

For comparison purposes (for example, one by one) you will be fine, but otherwise the code you have will lead to undefined behavior.

Read more about Wikipedia's undefined behavior .

+2
source

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

+1
source

All Articles