A new character array will not be initialized to all zeros

I am trying to allocate memory for a string of variable length n . Here is my attempt:

 int n = 4; // Realistically, this number varies. char* buffer = new char[n * 512](); printf("buffer[0:3] = [%d][%d][%d][%d]\n", buffer[0], buffer[1], buffer[2], buffer[3]); 

I understand that enclosing () at the end should initialize all elements to zero. However, I noticed the opposite. Here is the output to the console:

 buffer[0:3] = [-120][-85][-45][0] 

How to make the new initializer work correctly?

Note. I know that I can use std::fill , but I'm curious why the new initializer does not work as advertised .

edit: Here is my revised approach with std::fill , which gives the correct behavior. But I would still like to know why this is necessary.

 int n = 4; // Realistically, this number varies. char* buffer = new char[n * 512](); std::fill(&buffer[0], &buffer[n * 512], 0) printf("buffer[0:3] = [%d][%d][%d][%d]\n", buffer[0], buffer[1], buffer[2], buffer[3]); 

It is output:

 [0][0][0][0] 
+6
source share
1 answer

I understand that turning on () at the end should initialize all elements to zero.

You're right. In C ++ 98, C ++ 03, and C ++ 11 (all with slight differences in wording), empty parentheses mean that the new ed array will be initialized in such a way that the char elements will ultimately be zero initialized.

C ++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-11). The flags that I pass are: -m32 -fPIC -O2

gcc 3.4 has been around for almost ten years now, and it is not surprising that this error would be a mistake. In fact, I think that I vaguely recall almost the same error that was filed against gcc over the past four or five years. This error I'm thinking of was related to the syntax:

 new int[x] {}; 

It would be nice if writing portable code meant reading the C ++ specification, and then writing code with the desired behavior in accordance with the specification. Unfortunately, this most often means writing code that works with bugs in all implementations you care about.

+8
source

All Articles