I have the following code segment:
token = strtok(line, separator);
i = 0;
args[i++] = token; /* build command array */
while( token != NULL ) /* walk through other tokens */
{
/* printf( " %s\n", token ); */
token = strtok(NULL, separator);
if (strcmp(token, "|") != 0) {
printf("entered");
}
else {
args[i++] = token;
} /* and build command array */
The code compiles fine, but upon execution passing any argument, I receive the error "Segmentation fault (Core dumped)". Removing the if statement comparing the 2 strings solves the issue, so it is a problem with that comparison.
When strtok
does not find next token it returns NULL
, thus the segfault when trying to strcmp(NULL, "|")
Test if token
is null before strcmp
.
the posted code:
token = strtok(line, separator);
i=0;
args[i++]=token; /* build command array */
while( token != NULL ) /* walk through other tokens */
{
/* printf( " %s\n", token ); */
token = strtok(NULL, separator);
if (strcmp(token, "|") != 0) {
printf("entered");
}
else {
args[i++] = token;
} /* and build command array */
contains a logic error. the returned value from strtok()
is being used before being checked.
suggest something similar to:
i=0;
token = strtok(line, separator);
while( token != NULL ) /* walk through other tokens */
{
/* printf( " %s\n", token ); */
if (strcmp(token, "|") != 0)
{
printf("entered");
}
else
{
args[i++] = token;
} /* and build command array */
...
token = strtok(NULL, separator);
} // end while
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.