Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point does memory allocated by malloc get a type?

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?

like image 516
vitaut Avatar asked Mar 15 '16 23:03

vitaut


2 Answers

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.

like image 151
T.C. Avatar answered Oct 03 '22 07:10

T.C.


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.

like image 29
david.pfx Avatar answered Oct 03 '22 06:10

david.pfx