Junk after C++ string when returned

前端 未结 2 1039
挽巷
挽巷 2021-01-28 07:49

I\'ve just finished C++ The Complete Reference and I\'m creating a few test classes to learn the language better. The first class I\'ve made mimics the Java StringBuilder class

2条回答
  •  借酒劲吻你
    2021-01-28 08:09

    Does index contain the length of the string you're copying from including the terminating null character? If it doesn't then that's your problem right there.

    If stringArrary isn't null-terminated - which can be fine under some circumstances - you need to ensure that you append the null terminator to the string you return, otherwise you don't have a valid C string and as you already noticed, you get a "bunch of junk characters" after it. That's actually a buffer overflow, so it's not quite as harmless as it seems.

    You'll have to amend your code as follows:

    char *copy = new char[index + 1];
    

    And after the copy loop, you need to add the following line of code to add the null terminator:

     copy[index] = '\0';
    

    In general I would recommend to copy the string out of stringArray using strncpy() instead of hand rolling the loop - in most cases strncpy is optimized by the library vendor for maximum performance. You'll still have to ensure that the resulting string is null terminated, though.

提交回复
热议问题