简体   繁体   中英

Can anyone please explain what this C++ code is doing?

char b = 'a';
int *a = (int*)&b;
std::cout << *a;

What could be the content of *a ? It is showing garbage value. Can you anyone please explain. Why?

Suppose char takes one byte in memory and int takes two bytes (the exact number of bytes depends of the platform, but usually they are not same for char and int). You set a to point to the memory location same as b . In case of b dereferencing will consider only one byte because it's of type char. In case of a dereferencing will access two bytes and thus will print the integer stored at these locations. That's why you get a garbage: first byte is 'a' , the second is random byte - together they give you a random integer value.

You initialize a variable with the datatype char ... a char in c++ should have 1 Byte and an int should contain 2 Byte. Your a points to the address of the b variable... an adress should be defined as any hexadecimal number. Everytime you call this "program" there should be any other hexadecimal number, because the scheduler assigns any other address to your a variable if you start this program new.

Either the first or the last byte should be hex 61 depending on byte order. The other three bytes are garbage. best to change the int to an unsigned int and change the cout to hex.

I don't know why anyone would want to do this.

Think of it as byte blocks. Char has one byte block (8 bits). If you set a conversion (int*) then you get the next 7 byte blocks from the char's address. Therefore you get 7 random byte blocks which means you'll get a random integer. That's why you get a garbage value.

The code invokes undefined behavior, garbage is a form of undefined behavior, but your program could also cause a system violation and crash with more consequences.

int *a = (int*)&b; initializes a pointer to int with the address of a char . Dereferencing this pointer will attempt to read an int from that address:

  • If the address is misaligned and the processor does not support misaligned accesses, you may get a system specific signal or exception.
  • If the address is close enough to the end of a segment that accessing beyond the first byte causes a segment violation, that's what you can get.
  • If the processor can read the sizeof(int) bytes at the address, only one of those will be a , ( 0x61 in ASCII) but the others have undetermined values (aka garbage ). As a matter of fact, on some architectures, reading from uninitialized memory may cause problems: under valgrind for example, this will cause a warning to be displayed to the user.

All the above are speculations, undefined behavior means anything can happen.

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