Reputation: 873
I'm trying to learn C++ using the book "C++ for Lazy Programmers" and it gives the function myStrcpy
for copying two strings (page 306), which I used in this little example:
#include <iostream>
void myStrcpy(char* destination, const char* source);
int main()
{
char ca1[] = "this";
char ca2[] = " is a test of this.";
myStrcpy(ca1, ca2);
std::cout << ca1 << " \t " << ca2 << '\n';
}
void myStrcpy(char* destination, const char* source)
{
while (*source)
*destination++ = *source++;
*destination = '\0'; //put null character at the end
}
When I try to run the program, I get the following error:
*Run-Time Check Failure #2 - Stack around the variable 'ca1' was corrupted. The error does not appear when I switch the variables, so myStrcpy(ca2, ca1)
.
With my little knowledge of C++ and Google, I assume it is because myStrcpy
writes into areas where it has no business writing to (since the array that is being copied to is shorter than the other one), is that right?
And if that is the case, what would be the proper procedure to implement this be? Create a new character array and then overwrite the pointer to the old one? I assume one would still have to properly free up the memory from the old one then, is that correct or does C++ handle that automatically?
Thank you in advance for your time, it's really appreciated!
Upvotes: 0
Views: 121
Reputation: 106126
You're copying from ca2
- where the text " is a test of this."
is - into ca1
- which currently stores "this"
and therefore has been sized for four characters plus a NUL terminator. There's not enough room to copy into. You should make ca
bigger than whatever you want to copy into it, e.g.
char ca1[128] = "this";
More generally, in C++ it's best to use std::string
to manage memory for strings - it avoids a lot of error prone buffer allocation/size/deallocation logic. Using character arrays is a useful exercise to understand memory operations, but not good practice for general text handling. If you want to continue with character arrays as an exercise, the next steps are learning to dynamically allocate character arrays (new char[n]
), deallocate them (delete[] char_array
), and use strlen(const char*)
to find out the number of text characters (excluding the NUL terminator) in an existing buffer).
Upvotes: 4