I wrote a program that reads a command line from the standard input, and pass it to a function that is supposed to parse it into tokens.
This is the parsing function:
char** parse_cmdline(char* cmdline) {
char ** arr = malloc(10 * sizeof(char*));
for (int i =0 ; i < 10; ++i)
arr[i] = malloc(30 * sizeof(char));
char * token = strtok(cmdline, " ");
int i = 0;
while(token != NULL) {
if(i > 9) arr = realloc(arr, (i+10)*sizeof(char*) );
arr[i] = token;
token = strtok(NULL, " ");
i++;
}
printf("flag1");
return arr;
}
And this is how I am using it it main()
:
int main() {
int status;
pid_t pid;
pid = fork();
while(1) {
if(pid < 0) {
status = -1;
perror("Fork");
} else if(pid == 0) {
char* cmd;
printf("$");
if(fgets(cmd, sizeof cmd, stdin) == NULL) break;
parse_cmdline(cmd);
} else {
if( waitpid(pid, &status, 0) != pid ) {
status = -1;
}
break;
}
}
return 0;
}
This is an example of input that I supply to my program:
ls l a
The expected output should be:
l
(that is, the second argument, printed by my parse function)
And literally nothing happens. Not even the printf("flag1"); prints. But if I remove the char ** commands
and put the printf("%s", commands[0]);
in the parse_cmdline function, everything works, except im not assigning the return. Why and how to fix it?
As requested, here's the entirety of my code:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
char** parse_cmdline(char* cmdline) {
char ** arr = malloc(10 * sizeof(char*));
for (int i =0 ; i < 10; ++i)
arr[i] = malloc(30 * sizeof(char));
char * token = strtok(cmdline, " ");
int i = 0;
while(token != NULL) {
if(i > 9) arr = realloc(arr, (i+10)*sizeof(char*) );
arr[i] = token;
token = strtok(NULL, " ");
i++;
}
printf("%s\n", arr[1]);
return arr;
}
This part looks strange - see comments inline:
Perhaps you wanted to do a string copy instead - like:
Further this line seems strange:
You increase
arr
so that it can hold morechar*
but this time you don't allocate memory for the new strings as you did initially.