title: malloc(): memory corruption in a weird place
body: <p>I've been dealing with an annoying memory corruption error for a couple of hours. I've checked every related thread here, and I couldn't fix it. </p>
  
  <p>First of all, I'm writing a simple Terminal in C. I'm parsing the commands between pipe (|) and redirection (>, &lt;, etc.) symbols and place them in the queue. Nothing complicated!</p>
  
  <p>Here's the data structure for the queue;</p>
  
  <pre><code>struct command_node {
      int index;
      char *next_symbol;
      struct command_node *nextCommand;
      int count;
      char **args;
  };
  </code></pre>
  
  <p>When I'm storing small strings in the **args pointer, everything works just fine. However, when one of the arguments is long, I get malloc(): memory corruption error. For example, the following 1st command works fine, the 2nd command causes the error</p>
  
  <pre><code>   1st:  ls -laF some_folder | wc -l
  
     2nd:  ls -laF /home/enesanbar/Application | wc -l
  </code></pre>
  
  <p>I run the debugger, it showed that the malloc() call for the new node in the queue causes the error.</p>
  
  <pre><code>newPtr = malloc( sizeof(CommandNode) );
  </code></pre>
  
  <p>I'm carefully allocating the array of strings and freeing after I'm done with them as follows:</p>
  
  <pre><code>    char **temp = NULL;
      temp = malloc(sizeof(char*) * number_of_args);
  
      /* loop through the argument array */
      for (i = 0; i &lt; number_of_args; i++) {
          /* ignore the remaining commands after ampersand */
          if (strcmp(args[i], "&amp;") == 0) return;
  
          /* split commands by the redirection or pipe symbol */
          if (!isSymbol(args[i])) {
              temp[count] = malloc(sizeof(strlen(args[i])) + 1);
              strcpy(temp[count], args[i]);
              count++;
  
              /* if it is the last argument, assign NULL to the symbol in the data structure */
              if (i + 1 == number_of_args) {
                  insertIntoCommands(&amp;headCommand, &amp;tailCommand, temp, NULL, count);
                  for (j = 0; j &lt; count; j++) free(temp[j]);
                  count = 0;  // reset the counter
              }
  
          }
          else {
              insertIntoCommands(&amp;headCommand, &amp;tailCommand, temp, args[i], count);
              for (j = 0; j &lt; count; j++) free(temp[j]);
              count = 0;  // reset the counter
          }
      }
  </code></pre>
  
  <p>I must have missed something, or there's something I don't know about the **args fields and the allocation of the new node although it's nothing I haven't done before.</p>