Junk after C++ string when returned

前端 未结 2 1038
挽巷
挽巷 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.

    0 讨论(0)
  • 2021-01-28 08:11

    You need to null terminate the string. That null character tells the computer when when string ends.

    char * copy = new char[ length + 1];
    for(int i = 0; i < length; ++i) copy[i] = stringArray[i];
    copy[length] = 0; //null terminate it
    

    Just a few things. Declare the int variable in the tighest scope possible for good practice. It is good practice so that unneeded scope wont' be populate, also easier on debugging and kepping track. And drop the 'register' keyword, let the compiler determine what needs to be optimized. Although the register keyword just hints, unless your code is really tight on performance, ignore stuff like that for now.

    0 讨论(0)
提交回复
热议问题