This question asks what is the dynamic type of the object allocated by malloc
and according to the top answer:
The return value of
malloc
is a block of uninitialized storage. No object has been constructed within that storage. And therefore it has no dynamic type.
This brings another question: at what point does it make sense to say that the storage returned by malloc
gets a type. For example:
void *p = malloc(sizeof(int));
int *pi = (int*)p;
can we say that pi
above points to an object of dynamic type int
despite the fact that it is uninitialized?
The status quo according to the standard is that there's no object there.
[intro.object]/1:
An object is created by a definition ([basic.def]), by a new-expression ([expr.new]) or by the implementation ([class.temporary]) when needed.
See also the discussion in P0137, which would make the above quote the definition of object:
Drafting note: this maintains the status quo that
malloc
alone is not sufficient to create an object.
(int *)p
is none of these.
The answer is: when an object is created in the storage that malloc() allocates.
Note: malloc() is defined in the C standard and referenced in the C++ standard. Interactions with the C++ standard are intended for compatibility, not as a primary source.
What malloc() returns is a pointer to a unique region of storage (or NULL). It does not allocate or return an object. An object may be created in that storage by various means, and it is the object that has a type, not the storage.
The sample code given in the question creates a typed pointer, but has no effect on the storage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With