https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124832

            Bug ID: 124832
           Summary: Missing constraint diagnostic for string literal
                    initializer targeting a char subobject reached via
                    designator
           Product: gcc
           Version: 14.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: grant at kestrel dot edu
  Target Milestone: ---

GCC accepts a program that violates the scalar-initializer constraint in C17
6.7.9p11, even when compiled with "-std=c17 -pedantic". Clang also accepts the
program, but initializes the object differently.

This was tested locally on x86-64 GCC 14.1.0, on Ubuntu. The same behavior is
observed across versions on godbolt.

Reproducer:

#include <stdio.h>

struct {
    char str[16];
} hello = {
    "hello world",
    .str[6] = 'W',
    "ORLD"
};

int main(void) {
    printf("hello.str = \"%s\"\n", hello.str);

    printf("raw bytes: ");
    for (int i = 0; i < 16; i++) {
        printf("%d ", (unsigned char)hello.str[i]);
    }
    printf("\n");

    return 0;
}
Godbolt link: https://godbolt.org/z/sYhb3boYG

Expected behavior:
This program should be rejected with a constraint diagnostic.
After "hello world" initializes str, the designator .str[6] = 'W' sets str[6],
and ISO/IEC 9899:2018 6.7.9p17 says that "initialization then continues forward
in order, beginning with the next subobject after that described by the
designator" -- i.e., str[7], a char. The next initializer "ORLD" is a string
literal of type char[5], which is not a valid initializer for a scalar per
6.7.9p11: "The initializer for a scalar shall be a single expression [...] the
same type constraints and conversions as for simple assignment apply."
Paragraph 14 authorizes a string literal to initialize an array of character
type, but str[7] is not an array, so p14 does not apply at this position.

Actual behavior:
GCC accepts the program and produces:
hello.str = "ORLD"
raw bytes: 79 82 76 68 0 0 0 0 0 0 0 0 0 0 0 0
That is, the string literal "ORLD" is treated as a fresh whole-array
initializer for str, restarting at index 0 and clobbering both the earlier
"hello world" and the designated 'W' at str[6].

Clang behavior:
Like GCC, Clang accepts the program without a constraint diagnostic, but
produces different output:
hello.str = "hello WORLD"
raw bytes: 104 101 108 108 111 32 87 79 82 76 68 0 0 0 0 0
It treats "ORLD" as continuing character-by-character from str[7], preserving
"hello " and the designated 'W'. A separate bug report has been filed with
Clang: https://github.com/llvm/llvm-project/issues/190858.

Reply via email to