Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New character array won't initialize 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]);

My understanding is that the inclusion of () at the end should initialize all elements to zero. However, I noticed otherwise. Here is the output to the console:

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

How do I make the new initializer work properly?

Note: I am aware that I can use std::fill, but I'm curious as to why the new initializer doesn't work as advertised.

edit: Here is my revised approach with std::fill, which gives the correct behavior. But I'd still like to know why it's 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]);

This outputs:

[0][0][0][0]
like image 711
tomocafe Avatar asked Feb 13 '14 22:02

tomocafe


1 Answers

My understanding is that the inclusion of () at the end should initialize all elements to zero.

You are correct. In C++98, C++03, and C++11 (all using slight differences in wording) the empty parentheses mean that the newed array will be initialized such that the char elements will ultimately be zero initialized.

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

gcc 3.4 is nearly a decade old now and it is not surprising that would have this bug. In fact I think I vaguely recall almost exactly this bug being filed against gcc sometime in the last four or five years. That bug I believe was about the syntax:

new int[x] {};

It would be nice if writing portable code meant reading the C++ spec and then writing code with the desired behavior according to the spec. Unfortunately it more often means writing code that works around bugs in all the implementations you care about.

like image 159
bames53 Avatar answered Oct 30 '22 08:10

bames53