使用指针在我自己的strcat中的总线错误

nei*_*992 1 c pointers strcat

我正在做strcat函数的指针版本,这是我的代码:

void strcat(char *s, char *t);

int main(void) {
   char *s = "Hello ";
   char *t = "world\n";

   strcat(s, t);

   return 0;
}

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

  while ((*s++ = *t++))
    ;
}
Run Code Online (Sandbox Code Playgroud)

这看起来很简单,但在我的Mac OS 10.10.3上运行时会出现总线错误.我看不出为什么......

Sou*_*osh 5

在你的代码中

char *s = "Hello ";
Run Code Online (Sandbox Code Playgroud)

s指向驻留在只读内存位置的字符串文字.所以,问题是双重的

  1. 尝试更改字符串文字的内容会调用未定义的行为.

  2. (几乎忽略第1点)目标指针没有足够的内存来保存连续的最终结果.内存溢出.再次未定义的行为.

您应该使用一个具有足够长度数组(位于读写内存中)来保存生成的(最终)字符串(没有内存溢出).

建议:不要对用户定义的函数使用与库函数相同的名称.使用其他名称,例如my_strcat().

伪代码:

  #define MAXVAL 512
  char s[MAXVAL] = "Hello";
  char *t = "world\n";    //are you sure you want the \n at the end?
Run Code Online (Sandbox Code Playgroud)

然后

  my_strcat(s, t);
Run Code Online (Sandbox Code Playgroud)