Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty string literal in a multidimensional array decay to a null pointer?

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?

like image 298
Vilhelm Gray Avatar asked Nov 27 '19 18:11

Vilhelm Gray


Video Answer


1 Answers

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.

like image 93
Vilhelm Gray Avatar answered Nov 08 '22 21:11

Vilhelm Gray