[英]Segmentation fault using strcmp (Ubuntu)
我有以下代碼段:
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 */
代碼可以正常編譯,但是在執行時傳遞任何參數,都會收到錯誤“分段錯誤(核心已轉儲)”。 刪除比較兩個字符串的if語句即可解決此問題,因此該比較存在問題。
當strtok
找不到下一個令牌時,它返回NULL
,因此在嘗試strcmp(NULL, "|")
測試strcmp
之前token
是否為null。
發布的代碼:
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 */
包含邏輯錯誤。 在檢查之前,將使用從strtok()
返回的值。
建議類似以下內容:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.