4

I am looking at some old code of mine that manipulates data buffers. I have many places that have:

char *ptr1 ;
char *ptr2 ;

And then I need to find the number of bytes between the two.

int distance = ptr2 - ptr1 ;

I am getting a lot of warnings about truncation. What is the type of

 ptr2 - ptr1

I have found a number of answers dealing with pointer arithmetic but, oddly not an answer to this particular question.

Pointer Arithmetic

Community
  • 1
  • 1
user3344003
  • 20,574
  • 3
  • 26
  • 62
  • It may be that you are on a 64-bit platform which would mean that your pointers are actually 64-bit addresses. If you change the LHS type to a 64-bit integer the warning will probably go away. – klog Apr 07 '16 at 03:55

1 Answers1

8

The result of subtracting two pointers† is a std::ptrdiff_t. It is an implementation-defined signed integer; it could be larger than what an int could store.

See http://en.cppreference.com/w/cpp/types/ptrdiff_t for more information.

†You can only subtract pointers if they point to elements of the same array, otherwise it's UB.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • They are circular buffers so it works. I am shocked at the number of warnings from integer conversions in this code that was clean. The C++ gods have taken a path that is not sustainable. Has C++ added an integer cast with range checking? Cast long to short and checks that the value is within the short range? – user3344003 Apr 07 '16 at 14:04
  • @user3344003: I haven't been keeping up with the latest C++ stuff, so C++14 or beyond might have a utility, but I don't think so. IIRC Boost has `numeric_cast` which will do actual checking before constraining the range into a smaller target type. In your case, this would be overhead because you presumably have guarantees in the implementation that your buffer size fits within an `int`. This is a good use for `static_cast`, then, telling the compiler "I know this is safe, please use `int`". You may want to `assert()` this prior, as a safety precaution for future developers. – GManNickG Apr 07 '16 at 15:15