Home > Software engineering >  why string prints junk value,if we give it size?
why string prints junk value,if we give it size?

Time:11-10

#include <iostream>

using namespace std;

int main()
{
    string a("Hello World",20);
    cout<<a<<endl;
  
    return 0;
}

I get output as "Hello WorldP". Why? Usually we initialise string only with a data.But here i gave size.But it takes junkees. So do i prefer not giving size?

CodePudding user response:

Generally this is called garbage in, garbage out.

From cppreference:

Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if [s, s count) is not a valid range.

The behavior of your program is undefined because "Hello World" is a const char[12] and trying to access characters up to index 20 via the const char* (resulting from the array decaying to pointer to its first element) is out of bounds.


The actual use case for that constructor is to create a std::string from a substring of some C-string, for example:

std::string s("Hello World",5);  // s == "Hello"

Or to create a std::string from a C-string that contains \0 in the middle, for example:

std::string s("\0 Hello",5); // s.size() == 5 (not 0)
  • Related