2
votes

I am inspecting code that does not require explicitly casting result of malloc call but whenever I attempt to do this, the compiler throws an error.

i.e.

char *somevar;
somevar = malloc(sizeof(char) * n); //error
somevar = (char *)malloc(sizeof(char) * n); // ok
2
What error, exactly, are you getting? - Greg Hewgill

2 Answers

9
votes

This happens if you use C++ compiler instead of C compiler. As C++ requires explicit casting. The problem is not just with (un)casting malloc result, but any void pointer to other pointer.

1
votes

Did you remember to include the function prototype? For malloc(3), this is:

#include <stdlib.h>