Malloc confusion

2.6k views Asked by At

Hi after going through answer here

1: Do I cast the result of malloc? I understood that one of the reason why we do not cast malloc is that

casting malloc is redundant

But what I am still trying to figure out is the warning that will be suppressed when we do cast the malloc function

I also read this answer but I have the follwing doubts

#include<stdio.h>
main()
{
    int *a=malloc(20);
}

I understood the point in the answer that compiler will think that malloc returns an int while we are trying to give that value to an int * which will gives us error cannot convert from int * to int or something like that but the basic question is

Won't the compiler in absence of stdlib.h treat malloc as a user defined function and wont it look for the declaration of it and it will give some error related to missing delcaration/defination

2

There are 2 answers

2
AnT stands with Russia On BEST ANSWER

In the original C language - C89/90 - calling an undeclared function is not an error. For this reason, a pre-C99 compiler will not produce any "error" due to a missing function declaration. The compiler will simply assume that function returns an int.

It will also automatically and quietly "guess" (infer, derive) the function parameter types from the argument types you supplied in your call. In your example, you supplied 20, which will make the compiler to guess that the "unknown" malloc function takes a single parameter of type int. Note that this is also incorrect, because the real malloc takes a size_t parameter.

In C99 and later the function declaration is required. Which means that forgetting to declare malloc (e.g. forgetting to include <stdlib.h>) is indeed an error, which will result in a diagnostic message. (The parameter-guessing behavior is still there in the language though.)

Note also that in C99 and later declaring function main without an explicit return type int is illegal. The "implicit int" rule is specific to the original version of C language specification only. It no longer exists in C99 and later. You have to declare it as int main(... explicitly.

7
Gopi On

In the absence of stdlib.h the compiler thinks that the malloc() function will return int(For C89/90 and not from c99) and you are trying to assign that value to int * and hence there is a type mismatch and the compiler will report it