Search code examples
c++stringchargoogletest

google tests: can not create string from char array?


I run this test:

TEST_F(CHAR_TESTS, wtf){
  char letter[3] = {'A','B','C'};
  char types[2] = {'o','s'};
  char tmp[3];
  for(int i=0;i<3;i++){
    for(int j=0;j<3;j++){
      for(int k=0;k<2;k++){
        tmp[0]=letter[i];
        tmp[1]=letter[j];
        tmp[2]=types[k];
        std::string combination(tmp);
        std::cout << combination << std::endl;
      }
    }
  }
}

For some reason, this print this:

AAo~
AAs~
ABo~
ABs~
ACo~
ACs~
BAo~
BAs~
BBo~
BBs~
BCo~
BCs~
CAo~
CAs~
CBo~
CBs~
CCo~
CCs~

I do not think it is an issue with the printing itself, as I ended up doing this after noticing some tests comparing strings generated from char arrays were not passing, and I could not figure out why. So it feels like indeed the "combination" strings do not end up having the expected content.

The same code in a "regular" executable (not a gtest) print out what is expected (the 3 chars without the weird supplementary chars).


Solution

  • Unfortunately std::string does not have a constructor that takes a reference to array of char. So you end up invoking the const char* constructor, and this one requires the pointer to point to the first element of a null terminated string. Your char arrays aren't null-terminated, so you end up with undefined behaviour.

    You should null-terminate tmp, which you can do by declaring it with one extra character, and setting it to '\0'. You can achieve that like this

    char tmp[4] = {};