Click here to Skip to main content
15,795,793 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
  using namespace std;

  class TestClass

  str = nullptr;

  int length = strlen(str);

  this->str = new char[length + 1]; /* Why increase length + 1 here if everything works without it!? */

  for(int i = 0; i < length; i++)
  this->str[i] = str[i];
  cout << str[i] << endl;
  this->str[length] = '\0'; /* Why this line of code if everything works fine without it */

  delete[] this->str;



int main()
  TestClass a("Hello");

What I have tried:

I tried to run it but everything works without these constructs
Updated 27-Aug-23 16:15pm

The +1 is added to account for a terminating null character. That is what is added to the string to denote its end. The string "hello" you are using has five characters but six are needed to save the string due to the terminating null character.

Your code is working out of sheer luck. Apparently there is nothing on the heap beyond the string you have allocated so a null byte is just "lingering" there. In debug mode padding characters are added so that the diagnostic tools can detect this kind of error.
Share this answer
Everything works well because you are actually using this->str only inside the TestClass constructor and, there, you have the lenght of the passed string (such length is provided by the strlen function, which, in turn, relies on the '\0' terminator of the passed str in order to work properly).
As soon as the constructor code terminates, the length is lost: other methods (note, you haven't yet implemented any of them) should rely on the '\0' terminator in order to find the end of the string.

To summarize: any code dealing with strings should know the string length. You may use either the '\0' terminator (as C-like strings do or maintain the length of the string in a separate variable (as C++ std::strings do.

That said, Rick York considerations apply: if you are lucky, then, in memory, at the end of the Hello sequence of characters, there could be, by chance, a zero.
However, as a careful programmer, you shouldn't waste your share of luck on that.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900