Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 240
inconnu26 Avatar asked Nov 28 '25 16:11

inconnu26


1 Answers

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

like image 140
Marlon Avatar answered Nov 30 '25 07:11

Marlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!