https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69487
Bug ID: 69487
Summary: Unexpected VLA initialization of char[] from ""
Product: gcc
Version: 6.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: rogero at howzatt dot demon.co.uk
Target Milestone: ---
The initialization of a VLA char array from a string literal in C++ mode is
surprising: the code appears to copy a string literal starting with the NUL
character into the dynamically-sized buffer.
This is different from the (standard C/C++) treatment of the same syntax for a
fixed-size array.
--- vla-init.cxx ---
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void testfixed()
{
const int size = 6;
char buffer[size] = "";
for (int i = 0; i != size; ++i)
{
printf("Fixed: buffer[%i] = %2.2x\n", i, buffer[i] & 0xff);
}
}
int size = 6;
void testvariable()
{
char buffer[size] = "";
for (int i = 0; i != size; ++i)
{
printf("Variable: buffer[%i] = %2.2x\n", i, buffer[i] & 0xff);
}
}
int main()
{
testfixed();
testvariable();
}
--- ends ---
Sample output:
Fixed: buffer[0] = 00
Fixed: buffer[1] = 00
Fixed: buffer[2] = 00
Fixed: buffer[3] = 00
Fixed: buffer[4] = 00
Fixed: buffer[5] = 00
Variable: buffer[0] =00
Variable: buffer[1] =00
Variable: buffer[2] =00
Variable: buffer[3] =00
Variable: buffer[4] =01
Variable: buffer[5] =1b