You are using a wrong type to calculate the size in this call:
res = realloc(res, sizeof(char)*(index+1));
You need to use char*
, not char
, with sizeof
, like this:
res = realloc(res, sizeof(char*)*(index+1));
Since your code returns a pointer to C strings (represented as char*
) the return type should be char**
.
You need to remove the index == 0
condition from the while
loop, otherwise it wouldn't go past the initial iteration.
This assignment
res[index++]='\0';
should be
res[index++]=NULL;
You also need to call free(command)
before returning the results to the caller. Finally, you should not cast results of malloc
in C.
Here is your code after the fixes above:
char **read_command(char *text) {
int index=0;
char **res=NULL;
char *command= malloc(strlen(text)+1);
strcpy(command, text);
char *tok = strtok(command, " ");
while(tok!=NULL) {
res = realloc(res, sizeof(char*)*(index+1));
char *dup = malloc(strlen(tok)+1);
strcpy(dup, tok);
res[index++] = dup;
tok = strtok(NULL, " ");
}
// Need space to store the "terminating" NULL
// Thanks, BLUEPIXY, for pointing this out.
res = realloc(res, sizeof(char*)*(index+1));
res[index]=NULL;
free(command);
return res;
}