C 指针和字符串的分段错误

C 指针和字符串的分段错误,c,string,pointers,segmentation-fault,C,String,Pointers,Segmentation Fault,我正在编写C函数strcat的指针版本。它将字符串t复制到s的末尾。这是我的解决方案: /* strcat: a pointer version of the strcat (copy string t to the end of s) */ void strcat (char *s, char *t) { while (*s++ != '\0') /* find the end of s */ ; while (*s++ = *t++) ; }

我正在编写C函数strcat的指针版本。它将字符串t复制到s的末尾。这是我的解决方案:

/* strcat: a pointer version of the strcat (copy string t to the end of s) */
void strcat (char *s, char *t)
{
    while (*s++ != '\0')    /* find the end of s */
        ;

    while (*s++ = *t++)
    ;
}
我运行了它,它崩溃了-代码块调试器将其称为分段错误,函数的这一部分导致了崩溃:

while (*s++ = *t++)

我做错了什么?

这是固定版本和测试程序:

#include <stdio.h>

void strcat (char *s, char *t)
{
    while (*s++) 
        ;

    s--;

    while (*s++ = *t++)
        ;
}

int
main(void)
{
    char str1[100] = "abc";
    char *str2 = "def";
    strcat(str1, str2);
    printf("%s\n", str1);
    return 0;
}

然后您的程序可能会崩溃,因为编译器通常将字符串文本放在只读内存区域中,尝试写入这些位置将导致段错误。

写入
==
而不是
=
。您如何调用
strcat()
?分配了足够的内存吗?如果您显示更多的代码,这将很有帮助。顺便说一句,您的实现中有一个逻辑缺陷,在第一个
循环之后,
s
将指向第一个字符串
\0
之后的字符,您需要添加一个
s--while
循环之前,使用与标准函数相同的名称编写函数是未定义的行为(事实上,任何名称以
str
开头,后跟小写字母)。您应该将其称为其他名称,例如
my\strcat
。问题的另一个可能原因是,您实际上没有为
s
传递具有足够可写空间的缓冲区。请发布整个崩溃的程序。嘿,谢谢。我试着用这两个定义调用strcat。现在有道理了。
char *str1 = "abc";
char *str2 = "def";
strcat(str1, str2);