C++ Difference between new char[size] and new char[size]()

1k Views Asked by At

tldr; What is the difference between allocating memory for a primitive array with the parenthesis vs without them? e.g.

char * text = new char[size];

vs.

char * text = new char[size]();

Full Story:

I came across a strange issue today with some code I was writing. I created a class that contained a cstring member variable, text.

Class SomeClass
{
   private:
      char * text;
      ...
}

The constructor of said class would initialize text with dynamically allocated memory like so

text = new char[size];

When run, my program would prompt the user for input, store the input in the cstring, and display it back to the user. The problem was, when I used cout to display the cstring back to the user, garbage would appear on the end of the string. When I would step through the program with a debugger, the bug vanished, and the cstring would print normally. The problem only appeared when running the program, and never when stepping through with a debugger.

After making sure my cstring had the appropriate null terminating character, adequate memory was being allocated for the user input, array bounds were checked, and many other things, I finally fixed the issue by adding parenthesis after the square brackets when I allocated memory for the cstring like so

text = new char[size]();

Why did this fix my problem? What is the difference between allocating memory for a primitive array with the parenthesis vs without them?

1

There are 1 best solutions below

1
On

Thanks to Igor Tandetnik and M.M. in the comments. The parentheses initialize the chars in the array to 0 instead of garbage. This means that cout will stop printing chars at the first 0 it encounters instead of printing all the garbage contained in the string.