1

Of course I know that we don't cast the result of malloc(), but what about mkl_malloc()?

Here is the prototype: void* mkl_malloc (size_t alloc_size, int alignment);

It has the same return type as malloc(), as you can see: void* malloc (size_t size);

As a result, I would not cast the result, for these reasons. But the Intel people do, as you can see here, which makes me fear that I am missing something.

Does anybody know?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 4
    No, in C you don't need to cast *anything* returning `void *`. All pointers are implicitly convertible from and to `void *`. – Some programmer dude Aug 18 '15 at 10:33
  • Exactly @JoachimPileborg, but I am wondering if the Intel people have some other intention! That's why I asked and I think it would be good to get an answer, since I searched and found nothing. – gsamaras Aug 18 '15 at 10:34
  • 1
    If you check the prototype for `mkl_malloc` you see that is has some extra argument, right? That means it does *more* than just allocating a chunk of memory. And a `void *` is a `void *` no matter when or where it is. – Some programmer dude Aug 18 '15 at 10:36
  • Yes, it will align the memory @JoachimPileborg. I will agree. Should I wait for an answer so that a future user won't "waste" the same as me or delete the question? – gsamaras Aug 18 '15 at 10:39
  • 3
    There is a lot of code out there that has superfluous casts, but I don't think that this proves anything. People have habits (e.g they acquired when programming with another language such as C++). Sometimes these habits are bad, sometimes very bad. Cast are one of these, besides very specific, marginal use cases, good C code has no casts at all. – Jens Gustedt Aug 18 '15 at 10:44
  • 1
    d'accord @JensGustedt, that's what I had in mind, that C++ did somehow affected the example, I think that your comment combined with Joachim's could serve as an answer. – gsamaras Aug 18 '15 at 10:48

1 Answers1

5

Casting the result is superfluous and doesn't make much sense, so you shouldn't do it for that reason. But it is not super-important, it is a minor trifle.

The whole "cast the result of malloc" debate has gone out of proportion on Stack Overflow, and the most valid concerns of why you shouldn't went obsolete 16 years ago when implicit int was removed from the C language.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Does "implicit int" in the answer mean that before C99 the compiler assume malloc() returns an int when not including 'stdlib.h' to provide a prototype? – Eli4ph Jun 15 '17 at 11:22
  • 1
    @Eli4ph Indeed, on ancient compilers it would be dangerous to forget about stdlib.h in combination with casting the result of malloc. This is what triggered this whole debate. But such old compilers shouldn't be used - if they are then the main concern should be "why do I use a stone age compiler for" rather than "why do I cast the result of malloc". – Lundin Jun 15 '17 at 11:25