Firstly: K&R C is ancient.
Secondly: I don't know if that's the full code in that example, but in K&R C, functions are assumed to have an int
return value if not otherwise declared. If he's not declaring that malloc
, it means it returns int
as far as the compiler is concerned, hence the cast. Note that this is undefined behavior even in C89 (the earliest standarized version) and extremely bad practice; but he may have done it this way for brevity, or perhaps due to laziness --- or maybe for some other historical reason; I don't know all the intricacies of K&R C, and it might be that void*
to char*
casts were not implicit back then.
I should add that this is a very serious problem, since int
and void*
may have different sizes (and often do --- the most common example being most x86_64 code, where pointers are 64-bit, but ints are 32-bit).
UPDATE: @KeithThompson has informed me that the code is from 2nd edition, and malloc
is declared there. That one is (unlike 1st ed) still relevant, if very much outdated at places.
I'm guessing that the cast was likely done for compatibility with non-conforming compilers, which mattered at the time, as many [most?] compilers were not fully conforming yet. Nowadays, you'd have to get out of your way to find one that would need the cast (and no, C++ compilers don't count; they're C++ compilers, not C compilers).