Why copy method of std::string in C++ is showing weird behavior in this program?

Viewed 96
#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

The length of string is 26, when I tried to copy more than 23 characters, it is showing weird behavior (printing random character in the last) Here is the output of the above program

26

geeksforgeeks is for ge

geeksforgeeks is for gee£qí╜∙⌂
3 Answers

It's because you haven't set any '\0' (null) character to determine the end. That's why it's picking up garbage value.

you can do

#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
    ch1[23] = '\0';  
    ch2[24] = '\0';  
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

It's because your char[]'s are uninitialized and you don't place a \0 at the end of the strings after the copy.

Another solution is to initialize the char[]'s at construction:

char ch1[100]{};
char ch2[100]{};

You need to add null-terminator char by yourself; while std::string::copy doesn't do that.

E.g.

str1.copy(ch1,23,0);
ch1[23] = '\0';
str2.copy(ch2,24,0);
ch2[24] = '\0';
Related