c - 此 C 程序中的段错误

标签 c string strcpy string-literals

这是一个从 K&R 书中将 string1 复制到 string2 的程序。

#include <stdio.h>
void strcpy_m(char *t1, char *t2);

int main()
{
    char *s1 = "this is 1st";
    char *s2 = "this is second";
    strcpy_m(s1, s2);
    printf("%s\t%s\n",s1, s2);
    return 0;
}

void strcpy_m(char *t1, char *t2)
{
while((*t2 = *t1) != '\0'){
    t2++;
    t1++;
   }
}

在执行这个程序时,我遇到了段错误。原因是什么?

最佳答案

在您的代码中,s1s2 是指向 string literals 的指针。 。因此,这些指针所指向的内存位置的内容是不可修改的。任何更改内容的尝试都会调用 undefined behavior .

如果您想要一个可修改的字符串,请使用数组,例如

#define ARRSIZ 128  //just some arbitary number

char s1[ARRSIZ] = "this is 1st";
char s2[ARRSIZ] = "this is second";

关于c - 此 C 程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001990/

相关文章:

c - 如何分离特定数据

c - malloc 中的反向字符串

c - 段错误复制到节点中的字符串数组

string - Perl 6 中的 “P6opaque, Str” 与简单的 “Str” 类型

c - strncmp/strcpy 损坏源

jQuery 将字符串作为函数执行

string - scala,字符串变量处理为字符串而不是正则表达式

c - void 函数(不打印)- 使用递归反转字符串

c - C 中每第 n 列(K&R 1-22)折叠输入行

c - 检查 MISRA C 合规性的免费工具?