简体   繁体   中英

strcpy doesn't work on the same size arrays

When I try to assign value of one string to other using strcpy runtime error occurs. Below the code:

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;
}

Error is:

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

If I set the size of str2 equal to 6 or more program works well. What is a problem here?

strcpy operates on zero-terminated strings. Your char arrays don't have terminating zero bytes.

If it's working when you declare the arrays as [6] it's just by accident.

Function strcpy(); expects nul \\0 terminated string. str[] is not nul \\0 terminated.

Because you are printing array char by char in your code, you can rectify code as suggested by @ Karoly Horvath using memcpy instead of strcpy.

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

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

It is very risky to use string operations without forming null-terminated strings.

Here, strcpy() expects a null terminated string to be copied to a string which also has to be null terminated.

Therefore you must use:

  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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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