strcpy 不适用于相同大小的数组

strcpy doesn't work on the same size arrays

本文关键字:数组 不适用 适用于 strcpy      更新时间:2023-10-16

当我尝试使用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或更大,程序运行良好。这里有什么问题?

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

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

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

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

void*memcpy(void*destination,const void*source,size_t count);

memcpy(str2, str, sizeof(str));

在不形成以null结尾的字符串的情况下使用字符串操作是非常危险的。

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

因此,您必须使用:

  char str[6];
  char str2[6];
  str[0] = 'a';
  str[1] = 'b';
  str[2] = 'c';
  str[3] = 'd';
  str[4] = 'e';
  str[5] = '';
  strcpy(str2,str);