title: C code hits unexpected runtime error if I execute for loops sequentially instead of nested
body: <p>Full code <a href="https://gist.github.com/thMike/9e99d03fe99fa8d3bd58610dc9d6aa7a" rel="nofollow noreferrer">here</a>. Initial problem <a href="https://www.hackerrank.com/challenges/permutations-of-strings/problem" rel="nofollow noreferrer">here</a>.</p>
  
  <p>For some reason, this code runs perfectly:</p>
  
  <pre><code>for (int i = n - 2; i &gt; -1 ; i--)
  {
      if (strcmp(s[i], s[i + 1]) &lt; 0)
      {
          k = i;
          for (int j = n - 1; j &gt; k; j--)
          {
             if (strcmp(s[k], s[j]) &lt; 0)
             {
                l = j;
                swap(s, k, l);
                reverse_sequence(s, k + 1, n - 1);
                return 1;
             }
          }
      }
  }
  
  return 0;
  </code></pre>
  
  <p>While replacing the inner for with a break and writing it after the first for like this:</p>
  
  <pre><code>for (int i = n - 2; i &gt; -1 ; i--)
  {
      if (strcmp(s[i], s[i + 1]) &lt; 0)
      {
          k = i;
          break;
      }
  }
  for (int j = n - 1; j &gt; k; j--)
  {
      if (strcmp(s[k], s[j]) &lt; 0)
      {
          l = j;
          swap(s, k, l);
          reverse_sequence(s, k + 1, n - 1);
          return 1;
      }
  }
  return 0;
  </code></pre>
  
  <p>Hits a runtime error. Both print the permutations correctly.</p>
  
  <p>What is even happening here?</p>
  
  <p>Edit: If I add</p>
  
  <pre><code>if (i == 0 &amp;&amp; k == -1)
          return 0;
  </code></pre>
  
  <p>after the if in the first loop, it behaves as intended. So it's clear that what happens is that it compares s[-1] (k is initialized to -1) with something and it crashes.</p>