mini-gmp: cast to suitable type before left-shifting

Nickolai Zeldovich nickolai at csail.mit.edu
Sun Jan 6 21:42:16 CET 2013


mpz_import() in mini-gmp constructs a limb by left-shifting individual
bytes to different positions.  However, if sizeof(mp_limb_t)==8, then
the code ends up left-shifting a byte by 32 or more bits.  This is
undefined behavior in C.  (The byte is turned into an int for
left-shifting, and an int is often 32 bits; shifting a value by its
bitwidth or more is UB.)  This can produce unexpected results
depending on the compiler or CPU architecture used.

The attached patch avoids the problem by casting the byte to an
mp_limb_t first, so that the subsequent left shift is well-defined.

Nickolai.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: gp
Type: application/octet-stream
Size: 403 bytes
Desc: not available
URL: <http://gmplib.org/list-archives/gmp-bugs/attachments/20130106/a452bc23/attachment.obj>


More information about the gmp-bugs mailing list