0

I got very curious to know why we use casting to allocate heap memory by malloc in C language like instructions below:

#include<stdlib.h>

int main()
{
    double *var = (double*) malloc(sizeof(double));
    return 0;
}

Does malloc function return an appropriate address? If so, why do we use casting?

Thanks for answering.

  • Please see [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) Better is `double *var = malloc(sizeof *var);` – Weather Vane Sep 17 '20 at 15:50
  • 1
    If you're writing C code, you don't need to cast. It's only necessary for C++ because it refuses to implicitly cast void pointers. – Christian Gibbons Sep 17 '20 at 15:53
  • 1
    In C, a cast has not been required since the C89 standard. It was required in older K&R implementations, and most authors of reference manuals and tutorials in the '90s and early 2000s were accustomed to working in K&R C, so all their examples used casts. So that's how people learn it now, even though it's not necessary in C. It *is* necessary in C++, so if you're writing code to target both languages, you do need to use the cast. – John Bode Sep 17 '20 at 16:06

1 Answers1

1

You don't need to cast malloc, because it returns a void*. As wiki says: "The use of casting is required in C++ due to the strong type system, whereas this is not the case in C."

So, if you're working with C, you don't need to cast the malloc. But there are some advantages and disadvantages to do so:

Advantages:

  • Including the cast allows a program or function to compile as C++.
  • The cast allows for pre-1989 versions of malloc that originally returned a char *.
  • Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.

Disadvantages:

  • Under the ANSI C standard, the cast is redundant.
  • If the type of the pointer is changed, one must fix all code lines where malloc was called and cast (unless it was cast to a typedef).
Octaviotastico
  • 124
  • 5
  • 13
  • 2
    the most severe disadvantage is: the cast can hide a missing prototype. In that case the compiler assumes `malloc()` returns `int` which is cast to a pointer. That causes UB and very often crashes on 64 bit systems – Ingo Leonhardt Sep 17 '20 at 15:59
  • @IngoLeonhardt since C99 a warning is raised in this case (see [this](https://stackoverflow.com/questions/11171120/implicit-int-and-implicit-declaration-of-functions-with-gcc-compiler)). If can become critical only if warnings are ignored, that is never recommended in C. Anyway I appreciate the neutrality of this answer, despite the commonly accepted _dont-cast-malloc_ dogma. – Roberto Caboni Sep 17 '20 at 16:13