Skip to content

[intro.object] Converting a pointer value that is returned from a malloc operation that creates an array object to the element type results in UB? #378

Open
@xmh0511

Description

@xmh0511

Full name of submitter (unless configured in github; will be published with the issue): Jim X

The original question is on SO

[intro.object] p11 says:

Further, after implicitly creating objects within a specified region of storage, some operations are described as producing a pointer to a suitable created object. These operations select one of the implicitly-created objects whose address is the address of the start of the region of storage, and produce a pointer value that points to that object, if that value would result in the program having defined behavior.

Consider this example:

struct T{
    int a;
};
int main(){
  auto ptr = (T*)malloc(sizeof(T)*10); // #1
  ptr++;  // #2 UB?
}

Since T is an implicit-lifetime class, the operation malloc can implicitly create an object of class type T. In this example, we intend to make ptr point to the initial element of the array object with 10 elements of type T, based on this assumption, ptr++ would have a valid behavior. This case assumes the first element has its address at the start of the region.

Since an array of any type is an implicit-lifetime type, malloc(sizeof(T)*10) can implicitly create an array object with 10 elements and start the lifetime of that array object. Since the initial element and the containing array are not pointer-interconvertible.

That means, ptr either point to the first element of that array or that complete array. However, if we consider the first element locates at the start of the region, how do we prove whether this assumption is true or not? After all, there is no rule to say that array and its first element must have the same address.

Furthermore, consider this example:

struct S{
   S(){}
   ~S(){}
};
int main(){
  auto ptr = (S*)malloc(sizeof(S)*10); // #1
  ptr++; // #2
}

Now, S is not an implicit-lifetime class, must #1 and #2 be replaces to

auto arrPtr = (S(*)[10])malloc(sizeof(S)*10);  // point to the array
auto ptr =*arrPtr; // use array-to-pointer conversion 

to make ptr well-defined to point to the first element?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions