循环中的分段错误,无法找到错误

时间:2014-03-08 03:53:50

标签: c while-loop

我有以下代码完全正常,直到实现while循环,它给我一个分段错误,我无法找到它的位置。

#include <stdio.h>     /* for printf */
#include <stdlib.h>
#include <string.h>

int main (int argc, char **argv) {
    char str[200];
    char *tok = NULL;
    char path[300];

    strcpy(str, "a/b/c/d");

    printf("string before strtok(): %s\n", str);
    #string before strtok(): a/b/c/d
    tok = strtok(str, "/");
    strcpy(path,tok);
    printf("Current Tok: %s\n", tok);
    #Current Tok: a
    strcat (path,"/");
    printf("Current Path:%s\n",path);
    #Current Tok: a/

    while (1){
    strcat(path, "/");
    tok = strtok(NULL, "/");
    strcat(path, tok);
    printf("Path after strcpy:%s\n",path);
        if (tok == NULL){
            break;
        }
    }
}

我尝试手动完成,每一步都做得很好。

1 个答案:

答案 0 :(得分:6)

如果您在调试器中单步执行代码,或者在抛出异常时查看堆栈,您将看到错误在此处:

 tok = strtok(NULL, "/");

此点后的tok值为null。然后,您将该空指针值传递到

strcat(path, tok);

导致异常。我认为你需要在tok任务之后立即将你的“if”条件移动:

   tok = strtok(NULL, "/");
   if (tok == NULL)
        break;

如果您不熟悉使用调试器,那么请花点时间学习如何使用。这是你最好的朋友。

相关问题