title: C Exception thrown when function is ran for a second time
body: <p>This is core of the function i am currently writing.</p>
  
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;cstdlib&gt;
  #include &lt;cctype&gt;
  #include &lt;ctime&gt;
  #include &lt;cstring&gt;
  
  const char *words[] = {
      "pigu",
      // "third",
      // "country",
      // "human",
      // "define",
  };
  #define word_count (sizeof(words) / sizeof(char *))
  const char *allowed_chars = "abcdefghijklmnopqrstuvwxyz";
  
  const char *get_random_word()
  {
      return words[rand() % word_count];
  }
  
  char *copy(const char *origin)
  {
      char *str = NULL;
      str = (char *)malloc(sizeof(origin));
      strcpy(str, origin);
      return str;
  }
  
  int run()
  {
      const char *selected_word = get_random_word();
      char *active_word = copy(selected_word);
      char *placeholder_word = copy(selected_word);
      char *left_chars = copy(allowed_chars);
  
      free(active_word);
      free(placeholder_word);
      free(left_chars);
      return 1;
  }
  
  int main(int argc, char *argv[])
  {
      srand(time(NULL));
      while (run())
      {
      }
      printf("\n");
      return 0;
  }
  </code></pre>
  
  <p>I have stripped out other code and managed to locate the problem to <code>run</code> function, which in this case will run infinitely, however while debugging I have set break points inside <code>run</code> function. Turns out that after running the function <code>run</code> for second time, the program crashes when it tries to execute <code>free(placeholder_word);</code>. Why is this happening and how could i prevent it.</p>