inconnu26
inconnu26

Reputation: 45

Issue when I copy a char array to another, using a template

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];

Upvotes: 2

Views: 508

Answers (2)

Marlon
Marlon

Reputation: 20312

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).

Upvotes: 6

Alok Save
Alok Save

Reputation: 206536

To be able to copy the source buffer to destination you need the destination buffer big enough to hold the source buffer.

char two[5];

does not have enough space to store H,E,L,L,O,\0 ---> size is 6
So, Your destination array two should atleast have an size of 6, Otherwise your program writes beyond the bounds of the array and cause an Undefined Behavior.

Also, You should initialize your source buffer and NULL terminate it. Otherwise it contains junk characters.

char two[6]={0};

With the above mentioned modifications your program works as desired for me.

Upvotes: 4

Related Questions