简体   繁体   English

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

[英]Bus error in my own strcat using pointer

I'm doing a pointer version of the strcat function, and this is my code: 我正在做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++))
    ;
}

This seems straightforward enough, but it gives bus error when running on my Mac OS 10.10.3. 这似乎很简单,但是在我的Mac OS 10.10.3上运行时会出现总线错误。 I can't see why... 我不明白为什么...

In your code 在你的代码中

char *s = "Hello ";

s points to a string literal which resides in read-only memory location. s指向位于只读存储器位置的字符串文字 So, the problem is twofold 所以,问题是双重的

  1. Trying to alter the content of the string literal invokes undefined behaviour . 尝试更改字符串文字的内容会导致未定义的行为

  2. ( almost ignoring point 1 ) The destination pointer does not have enough memory to hold the concatinated final result. 几乎忽略了点1 )目标指针没有足够的内存来保存合并的最终结果。 Memory overrun. 内存溢出。 Again undefined behaviour . 再次是未定义的行为

You should use an array (which resides in read-write memory) with sufficient length to hold the resulting (final) string instead (no memory overrun). 您应该使用长度足够大数组 (驻留在读写内存中)来保存结果(最终)字符串(不占用内存)。

Suggestion: Don't use the same name for user-defined functions as that of the library functions. 建议:对于用户定义的函数,请不要使用与库函数相同的名称。 use some other name, eg, my_strcat() . 使用其他名称,例如my_strcat()

Pseudocode: 伪代码:

  #define MAXVAL 512
  char s[MAXVAL] = "Hello";
  char *t = "world\n";    //are you sure you want the \n at the end?

and then 接着

  my_strcat(s, t);

you are adding the text of 't' after the last addres s is pointing to 您要在最后一个addres s指向之后添加't'文本

char *s = "Hello ";
char *t = "world\n";

but writing after 's' is undefined behavior because the compiler might put that text in constant memory, in your case it crashes so it actually does. 但是在's'之后写入是未定义的行为,因为编译器可能会将文本放在常量内存中,以您为例,它崩溃了,实际上确实如此。

you should reserve enough memory where s points to by either using malloc or declare it array style 您应该使用malloc或声明其数组样式来保留s指向的足够内存

char s[32] = "Hello ";

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

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