在函数

时间:2016-05-29 21:42:21

标签: c string segmentation-fault malloc strcpy

我正在尝试编写一个接受路径(char *)的函数,并将其拆分为基于'/'分隔符的字符串数组。以下简化代码:

int split_path(char * path, char ** out) {
    out = NULL;
    char * token = strtok(path, "/");
    int count = 0;

    while(token) {
        out = realloc(out, sizeof(char*) * (++count));
        out[count-1] = malloc(sizeof(char) * strlen(token)+1);
        strcpy(out[count-1], token);
        fprintf(stderr, "%s\n", out[count-1]);

        token = strtok(NULL, "/");
    }   

    out = realloc(out, sizeof(char*) * (count+1));
    out[count] = NULL;

    return count;
}

int main(int argc, char * argv[]) {
    char path[] = "/home/pirates/are/cool/yeah";

    char ** out;

    int count = split_path(path, out);

    fprintf(stdout, "count: %d\n", count);
    fprintf(stderr, "1st: %s\n", out[0]); // segfaults here
    return 0;
}

split_path函数中的所有print语句都打印得很完美,输出如下所示:

count: 1, string: home
count: 2, string: pirates
count: 3, string: are
count: 4, string: cool
count: 5, string: yeah
count: 5
1st: ./a.out
[1]    5676 segmentation fault (core dumped)  ./a.out

但由于某种原因,当我回到main函数时,double-char-array不再有效。我认为这可能是因为它指向了在split_path函数中声明的内存,但是我正在strcpy来获取字符串,因此它不应该指向该函数本地的内存。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您对out参数管理不善。 out中的main()变量永远不会被分配有效的内存地址,因此也就是段错误。 out中的split_path()参数永远不会更新out中的main()变量。您需要将变量的地址传递给split_path(),以便它可以更新变量,并访问变量指向的内存。

另请注意,strtok()修改了它正在解析的字符串,因此您应该制作副本然后解析副本,以便原始文件不会被销毁。否则,请考虑使用strchr()代替strtok()

尝试更像这样的东西:

int split_path(char * path, char *** out) {
    *out = NULL;
    char * tmp = strdup(path);
    if (!tmp) { ... }
    char * token = strtok(tmp, "/"');
    int count = 0;
    char ** newout;

    while (token) {
        newout = realloc(*out, sizeof(char**) * (++count));
        if (!newout) { ... }
        *out = newout;
        (*out)[count-1] = malloc(sizeof(char) * (strlen(token)+1));
        if (!(*out)[count-1]) { ... }
        strcpy((*out)[count-1], token);
        fprintf(stderr, "%s\n", token);

        token = strtok(NULL, "/");
    }   

    newout = realloc(*out, sizeof(char**) * (count+1));
    if (!newout) { ... }
    *out = newout;
    (*out)[count] = NULL;

    free (tmp);
    return count;
}

int main(int argc, char * argv[]) {
    char path[] = "/home/pirates/are/cool/yeah";

    char ** out;

    int count = split_path(path, &out);

    fprintf(stdout, "count: %d\n", count);
    fprintf(stderr, "1st: %s\n", out[0]); // segfaults here

    free (out);
    return 0;
}

不要忘记错误处理。为简洁起见,我将其排除在此示例之外,但您不应将其从实际代码中删除。

相关问题