Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is, you do allocate a char* array inside <code>parse_command</code>, but the pointer to that array never gets out of the function. So <code>exec_command</code> gets a garbage pointer value. The reason is, by calling <code>parse_command(line, command)</code> you pass <em>a copy of the current value</em> of the pointer <code>command</code>, which is then overwritten inside the function - but <em>the original value is not affected by this!</em></p> <p>To achieve that, either you need to pass <em>a pointer to</em> the pointer you want to update, or you need to return the pointer to the allocated array from <code>parse_command</code>. Apart from <code>char***</code> looking ugly (at least to me), the latter approach is simpler and easier to read:</p> <pre><code>int main() { char** command = NULL; while (true) { fgets(line, MAX_COMMAND_LEN, stdin); command = parse_command(line); exec_command(command); } } char** parse_command(char* line) { char** command = NULL; int n_args = 0, i = 0; while (line[i] != '\n') { if (isspace(line[i++])) n_args++; } command = (char**) malloc ((n_args + 1) * sizeof(char*)); i = 0; line = strtok(line," \n"); while (line != NULL) { command[i] = (char *) malloc ( (strlen(line)+1) * sizeof(char) ); strcpy(command[i++], line); line = strtok(NULL, " \n"); } command[i] = NULL; return command; } </code></pre> <p>Notes:</p> <ul> <li>in your original <code>parse_command</code>, you allocate memory to <code>command</code> in a loop, which is unnecessary and just creates memory leaks. It is enough to allocate memory once. I assume that you want <code>command</code> to contain <code>n_args + 1</code> pointers, so I modified the code accordingly.</li> <li>in the last <code>while</code> loop of <code>parse_command</code>, you increment <code>i</code> incorrectly twice, which also leads to undefined behaviour, i.e. possible segmentation fault. I fixed it here.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload