Menu

#511 A compound literal without a storage class is not const

open
nobody
None
5
6 days ago
6 days ago
No

Bug #4044 reports &(struct A){1, 2} warning pointer target lost const qualifier. The warning is the smaller half of it: the object is also placed as a const one, which on mcs51 means code space, so a write through the pointer is a write to ROM.

struct A { int i; int j; };
struct A *p = &(struct A){1, 2};

void f (void) { p->i = 5; }

C11 6.5.2.5p4 gives a compound literal the type named in it, and nothing there adds a const, so the object is modifiable and its address is a pointer to non-const.

The parser infers constexpr for such a literal when the initializer allows it, which is worth knowing — printIvalStruct() uses it to follow a literal used as a struct initializer. But a constexpr the program declares is implicitly const (C23 6.7.2p6), and applying that to the inferred case changes the type the program sees.

The patch records whether the constexpr was inferred or written, and applies the implicit const only to the written one. A declared constexpr stays const, an explicitly const compound literal stays const, and the inferred case keeps the constexpr the initializer walk wants without acquiring a qualifier the program never asked for.

What the write actually does today, per port, on the test the patch adds:

stm8, f8, pdk14                  the write is silently lost
mcs51, mcs51 --model-large,      the program does not return
  ds390
ucz80, hc08, s08                 unaffected

Verification: the full regression suite on nine ports, 0 failures, with the device libraries rebuilt from clean against the same compiler — 287,752 test executions on r16743 plus this patch, and 288,067 on r16747 plus this patch (the second run also carries the union-alternative work drafted separately, which is where its extra 315 come from). The test the patch adds fails on six of those nine before it and passes on all nine after.

support/regression/tests/bug-4044.c carries the shape from the report, the nested one from the report, and writes through both a file-scope and a block-scope literal.

1 Attachments

Discussion


Log in to post a comment.