When trying to access individual bytes in C, why am I able to access bytes outside of the range of the type?

StackOverflow https://stackoverflow.com/questions/19072492

  •  29-06-2022
  •  | 
  •  

سؤال

I have a simple program in C that will allow me to access all bytes of an int. I am on a 32-bit machine.

int x = 1;
unsigned char* bytes = (unsigned char*)&x;  
printf("Value: %d\n", bytes[10000]); 

I don't understand why the last line prints 99 or is even a valid statement. An int on my machine should only have 4 bytes. I'd assume that bytes would only allow key values of 0-3.

What am I not understanding?

هل كانت مفيدة؟

المحلول

It's not a "valid statement" in that its behavior is undefined. However, it's not a constraint violation, and thus the compiler is not obligated (and not necessarily able) to tell you at compile-time that it's wrong. To know that it's wrong, the compiler would have to track what it points to, and although that's easy in your particular example, in general, it's not even possible.

When (at runtime) you perform the addition bytes+10000 (implicit in the expression bytes[10000]), the resulting behavior is undefined. Undefined behavior means all bets are off as to what your program does. There is no obligation for it to inform you that anything went wrong, nor to behave as you might hope it would.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top