0

Wouldn't the highest pointer be the one which can't be incremented through pointer arithmetic?

#include <iostream>

int main() 
{
    // Find the largest pointer
    int x = 0;
    int* px = &x;
    while ((px+1) != px)
      ++px;
    std::cout << "The largest pointer is: " << px;

    return 0;
} 

yields

Timeout

4 Answers4

7

As already mentioned, you've got an infinite loop because the condition can never be false.

That being said, what you're doing is undefined behaviour, illegal C++. Pointer arithmetic is only legal with pointers pointing to the same array (and a single object is treated as an array of one element) and right past the end of it. You can't expect a reasonable outcome of your program even if you fix the loop.

I suspect the value of std::numeric_limits<uintptr_t>::max() is the theoretical maximum value of pointer (converted to integer), but it might not be avaliable to your program. There are things such as virtual address space and segmented memory model to consider. Anyway, exact values of pointers (except for nullptr) is not something you should be concerned with. You get pointers by taking addresses of existing objects or by calling allocation functions and that's that.

N.B. I think you have a misconception that attempting to increment an integer type beyond its maximum value will just do nothing. That's incorrect - unsigned integers will wrap around to 0 and with signed integers you get undefined behaviour again (see signed integer overflow).

Hope that helps.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
3

This will never be false and thus never quit

while ((px+1) != px)
mvw
  • 5,075
  • 1
  • 28
  • 34
  • I hate it when my cat jumps on my notebook while I try to write an answer. Sigh. :-) – mvw Mar 25 '14 at 16:53
1

Look at this program:

#include <iostream>

int main()
{
  int *px = (int *) (~0);
  std::cout << "Value: " << px;
  ++px;
  std::cout << " Value: " << px << std::endl;  
}

whose output is:

Value: 0xffffffffffffffff Value: 0x3

As you can see, when you increment a pointer that is at its maximum, it values is reseted and begins again

Amadeus
  • 10,199
  • 3
  • 25
  • 31
  • 1
    ...but you can't rely on that with signed integers (it's undefined behaviour). – Cameron Mar 25 '14 at 17:10
  • @Cameron: It's also not defined for pointers. If p were cast to a uintptr_t and that one being incremented it made kind of weird sense. But that way... nope. – datenwolf Mar 25 '14 at 17:18
  • @datenwolf: Oops, read the code too quickly. That's what I meant :-) – Cameron Mar 25 '14 at 17:22
0

You might want to look for the largest pointer value that occurs before wrap-around, i.e.:

while (px+1 > px)
    px++;

...which will not work, of course, without the proper casts:

while ((unsigned long long)(px + 1) > (unsigned long long)px)
    px++;
David R Tribble
  • 11,918
  • 5
  • 42
  • 52