Title
Implicit object creation is insufficient to model effective type rule of C
Status
open
Section
7.2.1 [basic.lval]
Submitter
Jiang An

Created on 2025-07-04.00:00:00 last changed 1 month ago

Messages

Date: 2025-07-04.00:00:00

(From submission #723.)

Consider:

  #include <stdlib.h>

  int main() {
   void* p = malloc(sizeof(int) + sizeof(float));

   *(int*)p = 0;        // #1
   *(float*)p = 0.0f;   // #2
  }

This example has well-defined behavior in C, because C23 6.5.1p6 says

... If a value is stored into an object having no declared type through an lvalue having a type that is not a non-atomic character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value. ...

In contrast, implicit object creation for malloc happens once, and there is no single type that would make the program have defined behavior at both #1 and #2, since copy-assignment cannot create objects in C++.

Possible resolution:

Add to C.7.4 [diff.expr] as follows:

Affected subclause: 7.6.19 [expr.assign]
Change: Effective type rules are approximated with implicit object creation.
Rationale: C++ has a stronger type system than C.
Effect on original feature: Change to semantics of well-defined feature. Some well-defined C expressions will have undefined behavior in C++.
[Example:
  void f() {
    void* p = malloc(sizeof(int) + sizeof(float));

    *(int*)p = 0;
    *(float*)p = 0.0f;   // well-formed in both C and C++; undefined behavior in C++
  }
--end example]
Difficulty of converting: Programs must avoid implicit type changes of objects.
How widely used: Seldom.
History
Date User Action Args
2025-07-04 00:00:00admincreate