2

In C++ learning website (https://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/) there is a claim that GCC has a bug related to C-style string initialization when new operator is involved:

As of the time of writing, the GCC still has a bug where initializing a dynamically allocated array of chars using a C-style string literal causes a compiler error:

char *array = new char[14] { "Hello, world!" }; // doesn't work in GCC, though it should

I am using GCC version 7.4.0.

If I try to compile this excerpt I get:

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
     char *array = new char[14] { "Hello, world!" };

If I try to compile code like this:

char *array = new char[14] {'H', 'e', 'l', 'l', 'o', 0}

then it works as expected.

I am assuming this is considered a bug since:

char array[14]{ "Hello, world!" };

works as expected.

I could not find more information on this. Can anybody confirm or deny that this is a GCC bug?

Community
  • 1
  • 1
Dominic
  • 43
  • 3

1 Answers1

2

Yes it's a GCC bug. The relevant issue in the bug tracker is 77841. To quote the description over there:

5.3.4 New [expr.new] p.17.2
Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

8.5 Initializers [dcl.init] p.17.1
If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

8.5.4 List-initialization [dcl.init.list] p.3.2
Otherwise, if T is a character array and the initializer list has a single element that is an appropriately-typed string literal (8.5.2), initialization is performed as described in that section.

So the new expression in your question should be well-formed, just like the direct-initialization of the array object.

No prediction on when it's gonna be fixed. It's still reproducible in GCC's trunk as of writing this.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Look like [C++17 Standard - 11.6 Initializers(p12)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4741.pdf#section.11.6) in the C++17 standard also applies and initializers for dynamically allocated objects are treated no differently. – David C. Rankin Mar 08 '20 at 09:47