简体   繁体   中英

Can there be unitialized bits if I assign unsigned int to signed int

I have an unsigned integer (say 32 bit), When I assign this to a signed integer, Can there be uninitialized bits left in signed integer after conversion.

unsigned int i = 10 
int j = i;

I got an error from valgrind saying uninitialized bytes observed at

int func(long,int,int);

I see an unsigned int being passed to this func in third argument. I am suspecting can this unsigned-signed conversion cause this valgrind error

When you assign to a variable, you're assigning the value on the right hand side, not the object representation of the right hand side. So there will never be uninitialized bits (or bytes) after a variable has been assigned to.

Also, because a byte is the minimum addressable unit, you can't assign values to only certain bits in a byte. It's all or nothing.

It is possible to only assign to particular bytes of a variable if done via a char * or via memcpy . For example:

unsigned char c[] = { 1, 2 };
int j;
memcpy(&j, c, sizeof(c));

Supposing an int is 4 bytes, then only the first 2 bytes of j are written to and the last 2 remain uninitialized.

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