Norm said:
It does copy to the the string to the allocated char's by new correct?
Yes, strcpy is logically:
char* strcpy(char* to, const char* from) {
char* ret = to;
while(*to++ = *from++);
return ret;
}
But
in this example since the string does not fit I am getting an undefined
behavior?
Yes, as soon as strcpy attempts to write the string[5] it is undefined
behavior.
In my simple example what is being done with the extra char's that
don't fit?
It attempts to write them in string[5], string[6]... but that's not a defined
operation since those locations have not been allocated.
Is my compiler just seeing this and trying to fix the problem?
Because when I do (std::cout << string) the output is the entire string
literal.
The compiler doesn't know or care. That's the problem with undefined
behavior. It may or may not work at run time. If it printed it, you just
got lucky and the extra characters you wrote didn't hit anything.
All the str* functions and anything that treats char* as if it were a string
just starts marching through memory from the given pointer looking
for the first null character.
Here is another question to clarify this concept for me. If I were to do
this:
char *string;
string = new char[50];
strcpy(string, "This is the string");
std::cout << string;
strcpy(string, "This is another string");
std::cout << string;
I am assuming the second strcpy is starting over from the begging and
overwriting everything from the first strcpy. Would it have been better to
delete and reallocate memory for the new string?
No.... As long as you don't run off the 50 characters.
You don't even need to new anything, C++ is not JAVA.
char string[50];
would have worked just fine and you never have to remember to
delete it.
If you had used std::string, you wouldn't have to worry about running off
the end, and assignment would work as you expect.
BZZT. More undefined behavior. Anything you allocate with the array form of new
you need to deallocate with the array form of delete.
delete [] string;
string = new char[50];
strcpy(string, "This is another string");
std::cout << string;
Don't forget that you need to delete string here if you are done with it.