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

Asked

Viewed 1,582 times

9

I have a question about dynamic allocation in C.
At the time of allocating memory I have seen these two types of syntax:

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

But I don’t know what the difference is between them. Each site seems to say something different. Someone could explain to me the difference?

2 answers

8


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

Remember that the function malloc return a void*, or a generic type pointer, and you cannot use it directly without first converting it to the type you want.

Cast

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

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

Cast-less

ptr = malloc (sizeof(int));

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

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

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

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

Note that if you want to change the type of ptr for char* all instruction is still valid and there is no need to change anything else, in which case it will be converted to char*:

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

In addition it ends up giving more readability to the code 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));

2

The malloc function returns a pointer to a memory without type (void*), however, normally we use this memory with a pointer of some defined type and so the first line cast to (int*) (which indicates that ptr was of type int*). The second line ptr is of the void* type (otherwise it would be a build error).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.