I have always thought that when a variable is typecast, a copy of it results and any changes affect that temporary variable. But, the screenshot below indicates otherwise. Apparently, the original variable is what changes. Why? I am curious because I have never seen anything similar.
Asked
Active
Viewed 99 times
-1
-
Not always, but often, a type cast just **re-interprets** the bits that make up a certain type as the same bits the make up another type. But a cast can also cause a conversion, e.g. `(int)myFloat`. – Rudy Velthuis May 23 '17 at 22:06
-
2@RudyVelthuis no, a cast *never* does that. You can use it to obtain a type-punned pointer and reinterpret with that in some cases though. – Quentin May 23 '17 at 22:07
-
@Quentin: then what does the following cast do: `int a = -17; unsigned int b = (unsigned int)a;`. I would call that re-interpretation. – Rudy Velthuis May 23 '17 at 22:25
-
@RudyVelthuis see [the second bullet point here](http://en.cppreference.com/w/c/language/conversion#Integer_conversions). Everything is defined in terms of the represented value, not of the representation. An implementation might, for example, use sign-magnitude representation for negative integers, whose bits would not match these of the unsigned representation of that same number after the modulo. – Quentin May 23 '17 at 22:32
-
@Quentin: that describes conversions, not casts. – Rudy Velthuis May 23 '17 at 22:40
-
@RudyVelthuis A cast is an operator which performs a conversion – M.M May 23 '17 at 22:51
-
re-interpretation would be `unsigned int b = *(unsigned int *)&a;` , which may give a different value for `b` than the above code – M.M May 23 '17 at 22:52
-
@RudyVelthuis fair doubt. It looks like there's an error on cppreference on the "cast operator" page, so I'll quote the standard ([N1570, 6.3](http://port70.net/~nsz/c/c11/n1570.html#6.3)): "This subclause specifies the result required from [an] implicit conversion , as well as those that result from a cast operation (an explicit conversion)." -- then follows the bullet list I linked above ([6.3.1.3](http://port70.net/~nsz/c/c11/n1570.html#6.3.1.3)). – Quentin May 23 '17 at 22:52
1 Answers
4
sprintf
nul-terminates the string it outputs into the provided buffer. As the %010lu
format specifier requests a number padded to be at least 10 digits long, you are consistently overflowing crc_buf
and triggering UB. In your specific case, the least significant byte of crc
gets trampled.
Make crc_buf
11 characters or more, and use snprintf
instead of sprintf
to catch this class of errors. For maximal portability, you could also use the PRIu32
format macro instead of casting:
snprintf(crc_buf, sizeof crc_buf, "%10" PRIu32, crc);

Quentin
- 62,093
- 7
- 131
- 191