第一个malloc是错的..甚至'll you get when you derefer cmd by *cmd, before it'甚至分配了什么?
它也使用sizeof(char),这是错误的..
正确的方式是......
// strtok modifies the string. So use writable string
char line[80] = "Hello my name is anand";
char *token = strtok(line, sep);
int count = 0;
// Alloc array of char* for total number of tokens we have right now
char **cmds = (char **) malloc(sizeof(char*) * (count + 1));
while (token != NULL)
{
/**
* Alloc memory for the actual token to be stored..
* token returned by strtok is just reference to the existing string
* in 'line'
*/
cmds[count] = malloc(sizeof(char) * ((strlen(token) + 1)));
// Adds tokens to array of delimited commands
strcpy(cmds[count], token);
count++;
token = strtok(NULL, sep);
if (token != NULL)
{
// resize array of tokens to store an extra token
char ** newCmds = (char **) realloc(cmds, sizeof(char*) * (count + 1));
// only if realloc was successful then use it.
if (newCmds != NULL)
{
cmds = newCmds;
}
}
}