In the following code it seems that I can copy an entire large string into a small string.
So my question, how does that work? I only allocated 2 characters to str1, but it was able to store a longer string.
- Does this mean that strcpy is modifying memory on the stack that doesn't belong to us?
- Can arrays on the stack dynamically grow after its initialization?
- str1 size has not changed after the copy operation but it is holding a longer string. Thats bonkers!
I paste the code just make my point clearer:
char str1[2] = "a";
char str2[100] = "abcd";
cout<<"Before copying"<<endl;
cout<<"str1: "<<str1<<" size: "<<sizeof(str1)<<endl;
cout<<"str2: "<<str2<<" size: "<<sizeof(str2)<<endl;
strcpy(str1, str2);
cout<<"After copying"<<endl;
cout<<"str1: "<<str1<<" size: "<<sizeof(str1)<<endl;
cout<<"str2: "<<str2<<" size: "<<sizeof(str2)<<endl;