Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler assume that malloc returns an int?

Tags:

c

malloc

return

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?

like image 323
Kai Avatar asked Jan 23 '23 10:01

Kai


2 Answers

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.

like image 147
Nick Meyer Avatar answered Feb 01 '23 03:02

Nick Meyer


It's the default for every function.

My compiler tells me, if I didn't define a function, that int testFunction() is not defined.

like image 22
Burkhard Avatar answered Feb 01 '23 05:02

Burkhard