C 连接路径时出现错误

C 连接路径时出现错误,c,string,segmentation-fault,concatenation,C,String,Segmentation Fault,Concatenation,我编写这个函数是为了在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);

我编写这个函数是为了在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循环中得到segfault,在
*tmp2++=*tmp1++。有什么想法吗?

而(tmp1!=NULL)
不正确。
当(*tmp1!='\0')
时应为

指针本身永远不会变为空。正是它所指向的。

而(tmp1!=NULL)
是不正确的。
当(*tmp1!='\0')
时应为

指针本身永远不会变为空。正如它所指。

顺便说一句:
sizeof(char)*……
是多余的,因为它总是1。由C标准保证。顺便说一句:
sizeof(char)*…
是冗余的,因为它总是1。由C标准保证。