1

我编写了这个函数来加入 C 中的两条路径;

void *xmalloc(size_t size)
{
    void *p = malloc(size);
    if (p == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    return p;
}

char *joinpath(char *head, char *tail)
{
    size_t headlen = strlen(head);
    size_t taillen = strlen(tail);
    char *tmp1, *tmp2;

    char *fullpath = xmalloc(sizeof(char) * (headlen + taillen + 2));
    tmp1 = head;
    tmp2 = fullpath;
    while (tmp1 != NULL)
        *tmp2++ = *tmp1++;
    *tmp2++ = '/';
    tmp1 = tail;
    while (tmp1 != NULL);
        *tmp2++ = *tmp1++;
    return fullpath;
}

但是我在第一个 while 循环中遇到了段错误,在*tmp2++ = *tmp1++;. 有任何想法吗?

4

1 回答 1

4

while (tmp1 != NULL)是不正确的。
应该是while (*tmp1 != '\0')
指针本身永远不会变为 NULL。正是它所指向的。

于 2012-05-20T06:44:08.317 回答