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.
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;
So my question, how does that work?
Poorly. It doesn't do any checks whatsoever to confirm that the operation you're doing makes sense. You're the one responsible for checking that (which obviously leads to bugs).
strcpy
is generally just byte-copying loop. It will write the data into increasing addresses. As long as the memory you're writing to is "yours", after such copy printing the string will work just fine; the issue is what's actually in the memory you've overwritten.
strcpy
ask you to provide adequate output storage.sizeof
. What you might be thinking about is strlen
.All in all, never use C functions in C++ unless you have a very good reason to, use std::string
and none of those issues will happen. In fact, that's what your compiler could have told you:
Error C4996
strcpy
: This function or variable may be unsafe. Consider using strcpy_s instead.
If you listened, here's what you could get when running the program:
Those additional checks, however, are not a replacement for a well-written, well behaved program.