0

In this question, someone suggested in a comment that I should not cast the results of malloc, i.e:

int *sieve = malloc(sizeof(int)*length);

Rather than:

int *sieve = (int *)malloc(sizeof(int)*length);

Why would this be the case?

EDIT
Marked as duplicate cause I did not research enough.

Community
  • 1
  • 1
NULL
  • 313
  • 1
  • 12

1 Answers1

9

In C, you can implicitly convert from a void* (the return type of malloc) to any other pointer type. Therefore, the cast isn't required, and it's considered good C style to leave the cast off.

In C++, you cannot implicitly convert from a void* to any other pointer type, so the cast would be required. That said, in C++, you should almost certainly be using new and delete rather than malloc, as they're more type-safe, play well with constructors and destructors, etc.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    new and delete are different. They create objects as well as allocate memory. If you are writing an allocator that is going to just get memory you might implement it with malloc. Of course you are not going to just rewrite malloc, so perhaps you are going to do something else clever with it too. – CashCow Jan 22 '14 at 19:13
  • 1
    @CashCow In C++, wouldn't `operator new` and `operator delete` be more appropriate low-level allocators? – templatetypedef Jan 22 '14 at 19:36