Here is my code:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
template <class T1, class T2>
void copy2(const T1 source[], T2 destination[] , int size){
for (int i=0 ; i < size ; ++i){
destination[i]=static_cast<T1>(source[i]);
}
}
int main() {
const char one[] = "hello";
char two[5];
cout << "one: " << one << endl;
cout << "two: " << two << endl;
copy2(one, two, 6);
cout << "one: " << one << endl;
cout << "two: " << two << endl;
return 0;
}
but it outputs:
one: hello
two:
one:
two: hello
Moreover, the array "one" is const, and therefore shouldn't be changed.
PS: When I initiate the array "two" in the following way, it works (but WHY??):
char two[8];
However when I initiate it in both of the following ways, I get weird errors:
char two[6];
or
char two[7];
My best guess is that two and one are on the stack next to each other like this:
t w o - - o n e - - -
--------------------------------------------
| | | | | | h | e | l | l | o | \0 |
--------------------------------------------
Since you are overflowing two's buffer by passing size 6 to copy2 when two has size 5, the memory will end up like this:
t w o - - o n e - - -
--------------------------------------------
| h | e | l | l | o | \0 | e | l | l | o | \0 |
--------------------------------------------
Which is why two appears to hold "hello" and one shows nothing (since two overran its buffer and now the null terminator is the first character in one).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With