Search code examples
cc-stringsstrcpy

strcpy() unusual behaviour in C


so I decided to test out how strcpy() works and while reading the Linux Programmer's Manual. I came across the definition of strcpy

The strings may not overlap, and the destination string dest must be large enough to receive the copy.

So from this I can probably concur that the size of the destination string should be equal to or greater than the source string. But when I try to run the followng program in CLion, I get a smash stacking error

#include <stdio.h> 
#include <string.h>
int main()
{  
   char str1[7], str2[3] = "Hiy";
   strcpy(str1, str2);
   printf("%s", str1);
}

Here the size of str1 well exceeds the size of str2. In the ideal case, the strcpy should copy "Hiy" to str1 and then the print function should display "Hiy" but still I am getting the same smash stacking error.
I think it may have something to do with str2 having no null character (since I have filled the entire character array with characters) but I'm not sure. Any thoughts on why this isn't working?


Solution

  • Since the null character is attached end of the string you can't store str2[3] = "Hiy"; because array str2 has only 3 slots and your string has 4 characters including empty string char at end.Replace that with str2[4] = "Hiy"; Then you'll be able to have your intended output.