1

Can someone please explain to me the difference between

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

&&

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

Thanks!

Haris
  • 12,120
  • 6
  • 43
  • 70
Oliver Atienza
  • 631
  • 4
  • 8
  • `malloc` returns a void pointer. As you are assigning it to `int` pointer, it's always good to type cast. It won't make any difference in code but you will avoid one warning. – Swanand Nov 19 '15 at 08:28
  • @Swanand, you will not get any warning if you don't type caste the return of `malloc()`. – Haris Nov 19 '15 at 08:29
  • 1
    Its compiler dependent. eg, If you are writing `C` program in a `C++` compiler, then you need to cast. – SKD Nov 19 '15 at 08:37
  • @Swanand `malloc`'s return is `void*`, this means that in `C` there is no need to `cast` `malloc`, but if you need to do that probably is because you are using `a wrong Compiler` or maybe the `wrong Language`. Now, could you please explain us why **it's always good to type cast.**? Trust me, there will be a big difference at some point by doing that. Please explain. – Michi Nov 19 '15 at 09:43
  • @Haris & @ Milchi Yes... You both are correct. My compiler is wrong. I tried with GCC and it was without any warning. I am using an eclipse based compiler with lot of saftey plugins (MISRA, Lint etc) that's why I got warning. – Swanand Nov 19 '15 at 09:46
  • @Swanand [Please take a look here](http://stackoverflow.com/questions/7545365/why-does-this-code-segfault-on-64-bit-architecture-but-work-fine-on-32-bit). – Michi Nov 19 '15 at 09:46

1 Answers1

2

The difference is that you are casting the return of malloc() in the second example. malloc() returns a void* pointer, which is automatically and safely promoted to any other pointer type in this case.

Therefore casting in this case is not required and should not be done. Check here.

Community
  • 1
  • 1
Haris
  • 12,120
  • 6
  • 43
  • 70