I wrote this function to join two paths in 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;
}
But I am getting segfault on first while loop, at *tmp2++ = *tmp1++;. Any ideas?
while (tmp1 != NULL)is incorrect.Should be
while (*tmp1 != '\0').The pointer itself never becomes NULL. Just what it points to.