Pointer offset comparison

Greetings everybody !

Is there a clean way to compare two pointers, in order to no know which one has the bigger offset ?
I need it because I have to write some array of bytes in blank chunks of memory allocated by an external lib, and I want to check if the pointer to the blank chunk plus the size of my array goes beyond the starting of the next object in memory. (I know its pointer)

According to the C++ standard : « If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified. »

So... The use of (&blankPointer[arraySize] < nextPointer) is unspecified in my case, both pointers are not located in a common array or object.

Does somebody know what I can do ?
I want to check if the pointer to the blank chunk plus the size of my array goes beyond the starting of the next object in memory.
Why? All you need to know is the size of the chunk itself. What does it matter where the "next" object is?

What if memory is structured like this? You have pointer 0x10000 and the "next" object is at 0x11000, and you want to write 4096 bytes, but what you don't know is that the interval [0x10800; 0x11000) has been allocated by an unrelated piece of code, perhaps the runtime. The check you're proposing would not tell you this, and you'd proceed to overwrite that memory and silently corrupt who-knows-what.
Last edited on
Provided you can deal with the situation described by Helios, use std::less.

http://en.cppreference.com/w/cpp/utility/functional/less
Yeah of course I can deal with the situation described by Helios. I have the guarantee that the lib won't write anymore, it'll only do read access, until the memory is free in some specific cases.

Thanks for the tip with std::less, I would never have imagined it exists, it seems to me that C++ gets more and more weird with time. I would have expected a more C-ish way of doing for a such low-level management, but std::less seems to work.

I'm marking the topic a solved, however I've still a little question : How would a C developer have solved this problem ?
Topic archived. No new replies allowed.