Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ptrdiff_t too small?

Tags:

c++

c

d

I've always wondered: isn't ptrdiff_t supposed to be able to hold the difference of any two pointers by definition? How come it fails when the two pointers are too far? (I'm not pointing at any particular language... I'm referring to all languages which have this type.)

(e.g. subtract the pointer with address 1 from the byte pointer with address 0xFFFFFFFF when you have 32-bit pointers, and it overflows the sign bit...)

like image 860
user541686 Avatar asked Feb 01 '11 07:02

user541686


3 Answers

No, it is not.

$5.7 [expr.add] (from n3225 - C++0x FCD)
When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the <cstddef> header (18.2). As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i − j provided the value fits in an object of type std::ptrdiff_t. Moreover, if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)-(P) has the same value as ((Q)-(P))+1 and as -((P)-((Q)+1)), and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object. Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.

Note the number of times undefined appears in the paragraph. Also note that you can only subtract pointers if they point within the same object.

like image 51
Matthieu M. Avatar answered Nov 10 '22 15:11

Matthieu M.


No, because there is no such thing as the difference between "any two pointers". You can only subtract pointers to elements of the same array (or the pointer to the location just past the end of an array).

like image 8
R.. GitHub STOP HELPING ICE Avatar answered Nov 10 '22 17:11

R.. GitHub STOP HELPING ICE


To add a more explicit standard quote, ISO 9899:1999 §J.2/1 states:

The behavior is undefined in the following circumstances:

[...]

-- The result of subtracting two pointers is not representable in an object of type ptrdiff_t (6.5.6).

like image 2
Cubbi Avatar answered Nov 10 '22 15:11

Cubbi