Consider the following code at http://cpp.sh/9afy:

#include <iostream>
#include <iomanip>

uint8_t S[256];
uint8_t T[256];

uint8_t K[] = {0};
const int k_len = 1;

uint8_t M[] = {0,0,0,0,0,0,0,0,0,0,0};
const int m_len = 11;
uint8_t result[m_len];

int main(){
  for(int i = 0; i <= 255; i++){
    S[i] = i & 0xff;
    T[i] = K[i % k_len];
  }
  
  uint8_t j = 0, swap_byte;
  for(int i = 0; i <= 255; i++){
    j = (j + S[i] + T[i]) & 0xff;
    swap_byte = S[i];
    S[i] = S[j];
    S[j] = swap_byte;
  }

  uint8_t i = 0, k = 0; j = 0;

  for(int c=0; c<m_len; c++){
    i = i + 1;
    j = (j + S[i]);
    swap_byte = S[i];
    S[i] = S[j];
    S[j] = swap_byte;
    k = S[ ( S[i] + S[j] ) & 0xff ];
    result[c] = M[i] ^ k;
  }
  return 0;
}

Running the above code at cpp.sh with c++11 -Wall -O2 throws warning:

 In function 'int main()':
37:20: warning: iteration 10u invokes undefined behavior [-Waggressive-loop-optimizations]
30:3: note: containing loop
 

I don't understand why xoring the M[i] and k causes the warning, if you comment in the line 52, the warning disappears.

EDIT Similarly, the code when compiled with g++ throws the similar warning.

1

There are 1 answers

0
MMJM On

As stated in the comments by dxiv, Nate, MSalters;
i iterates before being used as an index to M.
At the time that c == 10, i is already equal to m_len, which caused an undefined behavior, since it is already out of bounds.

So to fix the problem, make sure that i is always less than m_len, so that it doesn't go out of the bounds.