Search code examples
c++strcpy

How can the strcpy function copy a large string into a smaller string?


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.

  1. Does this mean that strcpy is modifying memory on the stack that doesn't belong to us?
  2. Can arrays on the stack dynamically grow after its initialization?
  3. 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;

enter image description here


Solution

  • 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.

    1. Yes, and you're "lucky" that it didn't break the 2nd string. The requirements for strcpy ask you to provide adequate output storage.
    2. Generally no, especially when it comes to arrays further up the stack.
    3. It's not the string size, it's the static array size obtained with 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:

    MSVCC strcpy error

    Those additional checks, however, are not a replacement for a well-written, well behaved program.