1

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?

Nurlan
  • 2,860
  • 19
  • 47
  • 64

3 Answers3

7

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
5

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));
Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
3

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);
Aakash Anuj
  • 3,773
  • 7
  • 35
  • 47