What is the difference between the syntax ptr = (int *) malloc (sizeof (int)) and ptr = malloc (sizeof (int))?

5

I have a doubt about dynamic allocation in C.
At the moment of allocating the memory I already saw these two types of syntax:

ptr = (int*) malloc (sizeof(int));
ptr = malloc (sizeof(int));

But I do not know the difference in use between them. Each site seems to say something different. Could someone explain the difference to me?

    
asked by anonymous 20.03.2018 / 21:11

2 answers

4

Both statements do the same, and the end result is the same, differing only in details of writing and portability.

I remember that the malloc function returns a void* , that is, a generic type pointer , and you can not use it directly without first converting it to the type you want.

With cast

ptr = (int*) malloc (sizeof(int));

In this case it explicitly converts void* to int* . This will make the code portable for some very old compilers or for c ++, although in c ++ it has better ways of allocating memory than the malloc .

No cast

ptr = malloc (sizeof(int));

Here the void* is automatically promoted to the type of pointer that has left, the ptr . It means that if ptr is of type int* :

int *ptr = malloc (sizeof(int));

The void* is converted to int* by the compiler. This gives you more flexibility because if you have to change the type of ptr is less a place where you have to change things. You can do one more step in this direction if instead of putting sizeof(int) put the type in sizeof based on the pointer:

int *ptr = malloc(sizeof(*ptr));

Note that if you want to change the type of ptr to char* the whole statement is still valid and nothing else needs to be changed, in which case it will be converted to char* :

char *ptr = malloc(sizeof(*ptr));

In addition to this, it makes the code more readable because it is less extensive, especially when the types to be allocated are long.

Compare:

unsigned long long *ptr = (unsigned long long*) malloc(sizeof(unsigned long long));

With:

unsigned long long *ptr = malloc(sizeof(*ptr));
    
20.03.2018 / 23:28
1

The malloc function returns a pointer to an untyped (void *) memory, however, we will usually use that memory with a pointer of some defined type and so the first line cast for (int *) (which indicates that ptr was of type int *). The second line ptr is of the type void * (otherwise it would give compilation error).

    
20.03.2018 / 21:30