Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the dynamic type of the object allocated by malloc?

The C++ standard refers to the term "dynamic type" (and the C standard refers to "effective type" in the similar context), for example

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object,

But how is the dynamic type of the object allocated with malloc determined?

For example:

void *p = malloc(sizeof(int));
int *pi = (int*)p;

Will the dynamic type of the object pointed to by pi be int?

like image 919
vitaut Avatar asked Mar 15 '16 20:03

vitaut


2 Answers

According to the C++ specification:

Dynamic type:

<glvalue> type of the most derived object (1.8) to which the glvalue denoted by a glvalue expression refers

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.

The void* does not point to an object, and only objects have a dynamic type.

You can create an object within that storage by beginning its lifetime. But until you do so, it's just storage.

like image 129
Nicol Bolas Avatar answered Sep 28 '22 06:09

Nicol Bolas


In C, the effective type is only relevant when you access an object. Then in is determined by

  • the declaration type, if it has one
  • the type of another object of which it is a copy (eg. memcpy)
  • the type of the lvalue through which it is accessed, e.g if a void* is converted to another pointer type (e.g int*), which then is dereferenced.

The latter is usually what happens with malloced objects, if you assign the return value of malloc to a pointer type.

like image 31
Jens Gustedt Avatar answered Sep 28 '22 06:09

Jens Gustedt