-1

I’m curious why this causes the two compilers to produce different results

unsigned char* p = (unsigned char*)((char*)0-1);
int len = 4;
printf("%p\n",p);
if(p + len < p){
     printf("p + len < p");
}else{
     printf("p + len >= p");
}

My compiler: gcc 8.2.0 64-bit Release and VisualStudio2019 64-bit Release

gcc:

FFFFFFFFFFFFFFFF

p + len >= p

vs2019:

FFFFFFFFFFFFFFFF

p + len < p

1 Answers1

3

Pointer arithmetic is only defined if the result points inside the same object/array or one past its end. A null pointer doesn't point at an object so any pointer arithmetic on null is undefined.

Once you've invoked undefined behavior all bets are off. It's not just a theoretical concern. Compilers often do quite surprising things these days.

Moreover, pointer comparisons like >= are only well-defined when they're within the same object or array:

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.

If you hadn't already invoked undefined behavior the result would have been merely unspecified.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578