1

当我尝试使用strcpy运行时错误将一个字符串的值分配给另一个字符串时。代码下方:

int main (int argc, char **argv)
{ 
  char str[5];
  char str2[5];//if set size of str2 equal to 6, no error occurs

  str[0] = 'a';
  str[1] = 'b';
  str[2] = 'c';
  str[3] = 'd';
  str[4] = 'e';

  cout<<sizeof(str)<<endl;
  cout<<str[0]<<endl;
  cout<<str[1]<<endl;
  cout<<str[2]<<endl;
  cout<<str[3]<<endl;
  cout<<str[4]<<endl;

  strcpy(str2,str);

  cout<<sizeof(str2)<<endl;
  cout<<str2[0]<<endl;
  cout<<str2[1]<<endl;
  cout<<str2[2]<<endl;
  cout<<str2[3]<<endl;
  cout<<str2[4]<<endl;

  getch();
  return 0;
}

错误是:

Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted

如果我将 str2 的大小设置为 6 或更多,程序运行良好。这里有什么问题?

4

3 回答 3

7

strcpy对以零结尾的字符串进行操作。您的 char 数组没有终止零字节。

如果它在您声明数组时起作用,[6]那只是偶然。

于 2013-09-05T05:49:53.433 回答
5

函数strcpy();需要以 nul\0结尾的字符串。str[]不是 nul\0终止的。

因为您在代码中逐个字符地打印数组字符,所以您可以按照@Karoly Horvath的建议使用 memcpy 而不是 strcpy 来纠正代码。

void * memcpy ( void * 目的地, const void * 源, size_t 计数);

memcpy(str2, str, sizeof(str));
于 2013-09-05T05:48:10.010 回答
3

在不形成空终止字符串的情况下使用字符串操作是非常危险的。

在这里, strcpy() 期望将一个以空字符结尾的字符串复制到一个也必须以空字符结尾的字符串。

因此,您必须使用:

  char str[6];
  char str2[6];

  str[0] = 'a';
  str[1] = 'b';
  str[2] = 'c';
  str[3] = 'd';
  str[4] = 'e';
  str[5] = '\0';
  strcpy(str2,str);
于 2013-09-05T05:52:29.457 回答