繁体   English   中英

指针和字符串的分段错误

[英]Segmentation Fault with Pointers and Strings

我正在编写 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()

char *str1 = "abc";
char *str2 = "def";
strcat(str1, str2);

那么你的程序可能会崩溃,因为编译器通常会将字符串文字放在只读内存区域,尝试写入这些地方会导致段错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM