简体   繁体   中英

Malloc confusion

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

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 (eg 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.

在没有stdlib.h的情况下,编译器认为malloc()函数将返回int (对于C89 / 90而不是来自c99)并且您正在尝试将该值赋给int * ,因此存在类型不匹配和编译器会报告

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM