简体   繁体   English

指针和字符串的分段错误

[英]Segmentation Fault with Pointers and Strings

I am writing a pointer version of the C function strcat.我正在编写 C 函数 strcat 的指针版本。 It copies the string t to the end of s.它将字符串 t 复制到 s 的末尾。 This is my solution:这是我的解决方案:

/* 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++)
    ;
}

I ran it and it crashed - the Code Blocks debugger called it a segmentation fault, and that this part of the function was causing the crash:我运行它,它崩溃了——代码块调试器称它为分段错误,而这部分函数导致了崩溃:

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

What have I done wrong?我做错了什么?

Here is the fixed version and a test program:这是固定版本和测试程序:

#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;
}

If you call that strcat() in the following way,如果您按以下方式调用strcat()

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

then your program may crash, because compilers usually put string literals in read-only memory region, try to write to these places will cause segment fault.那么你的程序可能会崩溃,因为编译器通常会将字符串文字放在只读内存区域,尝试写入这些地方会导致段错误。

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

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