Should I cast the result of malloc (in C)?
In modern C programming, you generally should not cast the result of malloc
(or related memory allocation functions such as calloc
or realloc
). Here’s why:
-
No Cast Required in C
- In C,
malloc
returns avoid*
. An implicit conversion to any other pointer type (e.g.,int*
,char*
, a user-defined structure pointer, etc.) is automatically performed by the compiler. Therefore, explicitly writing something like(int*) malloc(...)
is not necessary.
- In C,
-
Potentially Masks Missing Includes
- If you forget to include
<stdlib.h>
(wheremalloc
is declared), the compiler will assumemalloc
returns anint
by default (in pre-C99 compilers or without proper warnings). Casting that assumedint
to some pointer type can hide the warning or error you’d otherwise get—potentially causing undefined behavior.
- If you forget to include
-
Consistency with C++
- Although C++ code typically uses
new
instead ofmalloc
, if you do usemalloc
in C++ for some reason, then you do need a cast (C++ does not allow an implicit conversion fromvoid*
). But for C codebases, this is irrelevant.
- Although C++ code typically uses
-
Historical Reason
- Older K&R compilers sometimes required casts, but modern conforming C compilers do not. This practice remains in some codebases primarily for historical reasons or cross-language code that might be compiled as C++.
Example
#include <stdlib.h> // for malloc int main() { int *arr = malloc(5 * sizeof(int)); // No cast needed in C if (!arr) { // Handle allocation failure } // Use arr... free(arr); return 0; }
- Correct (no cast):
int *arr = malloc(5 * sizeof(int));
- Works but discouraged (casting in C):
int *arr = (int *)malloc(5 * sizeof(int));
Recommended Resources
- Grokking Data Structures & Algorithms for Coding Interviews
- Grokking the Coding Interview: Patterns for Coding Questions
Conclusion
In C, don’t cast the result of malloc
. It’s unnecessary and can mask compiler warnings about missing function prototypes. Just be sure to include the relevant header (<stdlib.h>
) so that your compiler recognizes malloc
properly.
CONTRIBUTOR
TechGrind