此C程序中的分段错误

时间:2016-05-03 10:43:55

标签: c string strcpy string-literals

这是一个从K& R book中将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++;
   }
}

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

1 个答案:

答案 0 :(得分:2)

在您的代码中,s1s2string literals的指针。因此,这些指针中的任何一个指向的存储器位置的内容都是不可修改的。任何改变内容的尝试都会调用undefined behavior

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

#define ARRSIZ 128  //just some arbitary number

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