title: Memory Allocation of char** array in C
body: <p>I am writing a basic shell program in C for an assignment. I am currently having troubles allocating the memory that will be used to store the command line arguments that will be passed into the program to be parsed.</p>
  <p>I am getting a segmentation fault if the input size is greater than or equal to 4 (i.e. &quot;this is a test&quot; will produce a segmentation fault upon program terminations whereas &quot;this is a&quot; will not).</p>
  <p>I imagine my issue lies within how I was allocating the memory but the program is capturing each token that I enter and printing them to the screen.</p>
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  int main()
  {
    char cap[] = &quot;&quot;;
    char* cmd;
  
    const int MAX_ARGS = 16;
    const int MAX_ARG_SIZE = 256;
    char** arglst = (char**)malloc(MAX_ARGS * sizeof(char*));
    for(int i = 0; i &lt; MAX_ARGS; i++)
    {
      arglst[i] = (char*)malloc(MAX_ARG_SIZE * sizeof(char));
    }
  
    pid_t cpid;
    //implement ls, cd, mkdir, chdir, rm, rmdir
    while(1)
    {
      printf(&quot;Enter a command: &quot;);
      scanf(&quot;%[^\n]s&quot;, cap);
  
      int index = 0;
      cmd = strtok(cap, &quot; &quot;);
      while( cmd != NULL )
      {
        strcpy(arglst[index], cmd);
        cmd = strtok(NULL, &quot; &quot;);
        index++;
      }
  
      for(int i = 0; i &lt; index; i++)
      {
        printf(&quot;%s\n&quot;, arglst[i]);
      }
      printf(&quot;%d\n&quot;, index);
  
      /*
      if(strcmp(cap, &quot;quit&quot;) == 0) exit(EXIT_SUCCESS);
  
      if( (cpid = fork()) == -1) perror(&quot;fork()&quot;);
      else if(cpid == 0)
      {
        if( execvp(cmd, arglst) == -1 )
        {
          errorp(&quot;cmd error&quot;);
          exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
      }
      else
      {
        cpid = wait(NULL);
        strcpy(cmd, &quot;/bin/&quot;);
      }
      */
      for(int i = 0; i &lt; index; i++)
      {
        free(arglst[i]);
      }
      free(arglst);
      return 0;
    }
  
  }
  </code></pre>