I'm aware that in C it's best practice to never cast the return value of malloc()
. I've read that the compiler assumes that malloc()
returns an int if you don't include stdlib.h
. Of course it would produce an error if you tried to implicitly assign an int to something that's not an int, but that error could be covered up by an explicit cast -- hence the danger of explicitly casting malloc()
.
For any function I've created, if the function doesn't exist then the compiler will tell me so. Why does the compiler assume that malloc()
returns int even if you haven't included stdlib.h
? Shouldn't malloc()
just remain undefined until you include stdlib.h
?
Actually, if the compiler hasn't seen a declaration for any function you call (not just malloc) it will assume it is extern
and returns an int
. Most compilers I've used only give a warning for this, not an error, unless you turn up the warning level.
This goes back to the early days of C, I don't think this is allowed in C99.
@Michael's comment: You seem to be correct, according to K&R (page 72):
If a name that has not been previously declared occurs in an expression and is followed by a left parenthesis, it is declared by context to be a function name, the function is assumed to return an int, and nothing is assumed about its arguments.
It's the default for every function.
My compiler tells me, if I didn't define a function, that int testFunction()
is not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With