Reputation:
While I was using c_str()
to transform std::string
into C-style string, I didn't see the last character overridden by the null-termination which c_str()
is supposed to add in this program:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string s = "helloworld";
char c[10];
strcpy(c, s.c_str());
cout << c << endl;
return 0;
}
What I am asking is why d
is being printed (added to c
) as I was expecting null-termination to be there. What am I missing here?
Upvotes: 1
Views: 65
Reputation: 726579
Your code has undefined behavior, because c
, the array into which you copy the string, does not allocate enough space for null terminator.
The number of characters that you copy is 10, so you need an array of 11 to accommodate the null terminator.
To avoid overrun troubles like that with statically allocated arrays, use dynamic allocation instead:
char *c = new char[s.size()+1];
strcpy(c, s.c_str());
cout << c <<endl;
delete[] c;
Upvotes: 1
Reputation: 14159
strcpy
does not know how long the target array is. It copies until (and including) the terminating 0 byte. So, the whole string helloworld\0
is copied. Note that this is 11 chars and you might as well get a crash.
Upvotes: 0
Reputation: 36483
You have undefined behaviour, "helloworld"
is actually "helloworld\0"
, that is 11 characters. strcpy
tries to copy over the whole string including NUL but c
is only able to hold 10 characters.
Upvotes: 1