tags:

views:

307

answers:

4

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?

A: 

It's the default for every function.

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

Burkhard
A: 

All functions are assumed to return int by default unless otherwise specified.

See here.

John T
+7  A: 

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.

Nick Meyer
Actually, I'm pretty sure the compiler makes no assumptions about the number of parameters of an undeclared function. It's as if you declared it `int foo (...)` assuming that were possible (which I think it isn't, as varargs in standard C requires at least one required parameters). I don't have my copy of Harbison and Steele with me, though, so I might be wrong about this.
crosstalk
No, it's as if it was declared as `int foo()` - which is a function with as-yet-unspecified (but definite!) number of arguments; and not `int foo(void)` - which is a function with no arguments; or `int foo(...)` - which, as you say, is not valid.
Pavel Minaev
+1  A: 

Like @Burkhard said, it's the default. The compiler will spit out a warning if you haven't defined a prototype for the function, and it will assume the function returns an int. Then, if you really haven't defined it, the linker will be the one to give you an immediately-stopping error.

Mark Rushakoff