简体   繁体   中英

C++ undefined behavior

unsigned char * numbers = {1,1,1};
unsigned short * ptr = (unsigned short*) numbers;
*(++ptr)=2;

printf("%d %d %d %d", numbers[0], numbers[1], numbers[2], numbers[3]);

The above can result in undefined behavior, right? Also, what will be printed in the screen?

The result was 1 1 2 0 , but could 1 1 0 2 be printed sometime?

It will result in undefined behavior. First because you let a char pointer point to an integer array: note the difference between unsigned char * numbers = {1,1,1}; and unsigned char numbers[] = {1,1,1}; unsigned char* ptr = numbers; unsigned char numbers[] = {1,1,1}; unsigned char* ptr = numbers; .

But also because the program breaks the strict aliasing rule . Anything might happen: the program might print some sort of result, or rubbish, or crash.

Furthermore, your cast to unsigned short assumes a certain CPU endianess. So in case your program happens to go for the undefined behavior "print some sort of result", that result will depend on CPU endianess.

The above can result in undefined behavior, right?

(1) Not only the behaviour can be undefined, but it will always be undefined.

Also, what will be printed in the screen?

It is undefined as per (1)

will this in some computers print "1 1 0 2"

It might. Or it might not. It's possible because any outcome is possible. See (1).

We don't know for sure what the last character will be but the 1st 3 will be printed okay.

They might not be printed okay. See (1).

This particular piece of code:

unsigned char * numbers = {1,1,1};

will not compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM