top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why should I not cast the result of malloc in C?

+4 votes
179 views

I believe option 1 is more correct, dont know why?

1) int *p = malloc(sizeof(int)*l);
2) int *p = (int *)malloc(sizeof(int)*l);
posted Dec 10, 2014 by Salil Agrawal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

As we know return type of malloc() is (void *).

If you won't cast the return of malloc(), there is no problem in C because it allows void pointers to be implicitly converted to any other object pointer type.

But C++ does not.

So if you wanted to port your code to C++, it will give error.

Assume if you won't cast the malloc() and forget to include the stdlib.h where malloc() is declared.

Then by default C will assume that the function returns int. Here you will get a warning like assigning int to pointer.

Casting the result of malloc() in C will supress a useful diagnostic (i.e a valid warnig) if you forget to include stdlib.h and may face runtime issues.

Casting can help the developer identify inconsistencies in type sizing.

If the type of the pointer is changed, one must fix all code lines where malloc (if casted) was called.

answer Dec 10, 2014 by Arshad Khan
I am confused, I was in the impression that option 1 should always be used.
No, in C you can use both, as we know C allows void pointers to be implicitly converted to any other pointer type. So its not mandatory to cast the return of malloc.

Cast the return of malloc() will allows for older verison of malloc() which return a char *.

But in C++ you have to cast the return of malloc.
Thanks I got you, thanks for clarifying.
You are welcome :)
0 votes

yes, because the conversion from a pointer to void to a pointer to object is implicit.
A pointer to void may be converted to or from a pointer to any object type.
so,preferably use 1)case.

answer Dec 10, 2014 by Sridharan P
...