In table[var2 ^ string[i]];
, the var2
has an unsigned char
value of 0 to 255, and string[i]
may have a signed char
value of ?128 to +127. (We assume eight-bit bytes and two’s complement, which are ubiquitous in modern systems.)
As is usual with most C operators, the integer promotions are applied to the operands, which, in this case, produces int
operands. For the unsigned char
values 0 to 255, this produces an int
with bits set only in the low eight bits. For char
values ?128 to ?1, this produces an int
with bits set throughout the int
, particularly in the high bits.
Then the result of the XOR operation is an int
with high bits set, including the sign bit, so it has a negative value. Then table
is indexed with a negative subscript, going outside the bounds of the array. And so the behavior is not defined by the C standard.
To remedy this, change the element type of table
to unsigned char
or convert string[i]
to unsigned char
before using it in bitwise operations.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…