Why strcpy() works?

Hello,

I am allocating space only for two characters but it fits all of them, if you run this it will print the whole string literal "hello my friend". How is that possible?

I am using gcc 4.6.3., I know about strncpy().

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    char* str = new char[2];
    strcpy(str, "hello my friend");
    cout << str << endl;

    return 0;
}
Last edited on
strcpy(str, "hello my friend"); means "copy this thing on the right into the memory starting at the location that the pointer named str is pointing to".

So it does. It writes over str[0], and then str[1], and then the next byte (which could contain any data at all and you have no idea what you're writing over), and then the next byte (which could contain any data at all and you have no idea what you're writing over), and then the next byte (which could contain any data at all and you have no idea what you're writing over), and so on. Why would it stop you?

If you try to write over memory that the operating system thinks isn't yours, it will segFault. Clearly, the memory right after str[1] is not memory the OS thinks isn't yours. You're still trashing whatever data is there, though.

Then, this:
cout << str
This means "Output to screen the array of char that starts at the memory location str points to and finishes with a zero value". It does NOT mean "Output to screen str[0] and str[1]".
Last edited on
I see, thank you.
You can see the effect by rewritting your code the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    char s1[] "Am I alive?";
    char str[2];
    char s2[] "Am I alive?";

    strcpy(str, "hello my friend");
    cout << s1 << endl << str << endl << s2 << endl;

    return 0;
}
Hi Vlad,

I did run your snippet however str did not overwrite s2, I guess gcc did not place them in consecutive memory blocks - go figure.

Thx.
Last edited on
Topic archived. No new replies allowed.