This piece of code was working fine, until I modified it.
int main(int argc, char** argv)
{
char command[1024];
gets(command);
char *delim = " \t\f";
char **tokens;
int i=0;
/* Extracting tokens from command string */
for(tokens[i] = strtok(command, delim); tokens[i] != NULL; tokens[i] = strtok(NULL, delim))
{
i++;
}
return 0;
}
And here's the code that crashed with a Segmentation Fault on line
for(tokens[i] = strtok(command, delim); tokens[i] != NULL; tokens[i] = strtok(NULL, delim))
Code:
void commandProcess(char command[])
{
char *delim = " \t\f";
char **tokens;
int i=0;
/* Extracting tokens from command string */
for(tokens[i] = strtok(command, delim); tokens[i] != NULL; tokens[i] = strtok(NULL, delim))
{
i++;
}
}
int main(int argc, char** argv)
{
char command[1024];
gets(command);
process(command);
return 0;
}
I know that char command[]
decays to a pointer link, and also that strtok() modifies its first parameter and in my case it might be an undefined behaviour. link
So, could anybody please provide me some other way around, so that I can work out with the same function signature and still avoid the problem?
This seems a trivial problem, but I cannot make through it. :\ I even tried this,
void commandProcess(char command1[])
{
char command[1024];
int length = strlen(command1);
strncat(command, command1, length);
command[length] = '\0';
char *delim = " \t\f";
char **tokens;
int i=0;
/* Extracting tokens from command string */
for(tokens[i] = strtok(temp_command, delim); tokens[i] != NULL; tokens[i] = strtok(NULL, delim))
{
i++;
}
but then again crashes on the line
for(tokens[i] = strtok(temp_command, delim); tokens[i] != NULL; tokens[i] = strtok(NULL, delim))
I think that delim
& tokens
are not the culprits because the program without commandProcess() worked fine with them.