title: C trying to fix infinite loop
body: <p>I have a function that gets an index value, puts it in an array. Then generates a new new random index using rand + srand(<strong>key</strong>). And it checks if the newly generated index is in array already, it will will keep on generating new index and checking until a unique value is generated.</p>
  
  <p>The problem is that it works fine for small <strong>keys</strong>, but at longer keys it gets stuck in an infinite loop and can never find a unique value. Here's my code:</p>
  
  <pre><code>int getNewIndex(PPM *im, int index, int *visitedPixels, int *visitedPixelsIndex) {
  
      int i = 0;
      if(*visitedPixelsIndex == im-&gt;height) {
          perror("Cannot encode anymore: pixels limit reached");
          exit(1);
      }
  
      visitedPixels[*visitedPixelsIndex] = index;
      (*visitedPixelsIndex)++;
      // If index is already in the list, generate a new number and check again.
      while (i &lt; *visitedPixelsIndex) {
          if(index == visitedPixels[i]) {
              index = rand() % im-&gt;height;
              i = 0;
          } else {
              i++;
          }
      }
  
      return index;
  }
  </code></pre>
  
  <p>EDIT: <code>im-&gt;height</code> which is the image height is about 400-600 in average.</p>