8

I want to define a multidimensional C-string array, initialized by several string literals. In C I would do the following:

#include <stdio.h>

const char *strArr[2][1] = { {"foo"}, {""}};

int main(void) {
    printf("%p\t%p\n", strArr[0][0], strArr[1][0]);
    return 0;
}

Compiling with gcc -std=c18 -pedantic test.c and executing results in:

$ ./a.out 
0x55d95410f004  0x55d95410f008

As I expect, the empty string literal in strArr[1][0] decays to a valid pointer.


However, when I try the same code in C++:

#include <cstdio>

const char *strArr[2][1] = { {"foo"}, {""}};

int main(void) {
    printf("%p\t%p\n", strArr[0][0], strArr[1][0]);
    return 0;
}

Compiling with g++ -std=c++17 -pedantic test.cpp and executing results in:

$ ./a.out 
0x55c61494d004  (nil)

Here, the empty string literal in strArr[1][0] decays to a null pointer. Why does this happen in C++?


In the C++17 standard, I see the following in 5.13.5 paragraph 16:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (6.7).

This seems to indictate that an empty string literal, being an ordinary string literal, should have static storage duration. So why would an empty string literal decay to a null pointer?

20
  • 1
    Why use a C-style array in the first place? Why not std::array? Commented Nov 27, 2019 at 18:38
  • 2
    @super an empty string has one character: the terminator. When you print it, it outputs a valid nothing. Commented Nov 27, 2019 at 18:52
  • 3
    This is probably just a GCC 9 regression. You should report it and see what they say.
    – Brian Bi
    Commented Nov 27, 2019 at 18:53
  • 2
    g++ does this, clang doesn't: gcc.godbolt.org/z/XkZcVy Looks like a g++ bug. Commented Nov 27, 2019 at 18:57
  • 1
    @KeithThompson Account creation on the GCC bugzilla site is restricted, so I submitted an email request that will hopefully be fulfilled by tomorrow. For now, I have opened a bug report on Gentoo: bugs.gentoo.org/701364 Commented Nov 28, 2019 at 1:22

2 Answers 2

2

This behavior is not correct, and in this case is the result of a regression in GCC: https://gcc.gnu.org/PR90947

The regression has been fixed for GCC version 9.3 and should hopefully make it back to the earlier versions affected as well.

0

There is no such decay ; the output you observed is a compiler bug.

(Yes this is a short answer but there is nothing else to add).

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.