Mallock's Perplexity

Hi after passing the answer here

1 : Am I doing the malloc result? I realized that one of the reasons why we don’t throw malloc is because

casting malloc excessively

But what I'm still trying to figure out is a warning that will be suppressed when we press the malloc function

I also read this answer, but I have doubtful doubts

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

I understood the point in the answer that the compiler would think that malloc returns int, while we try to give this value int *, which will give us an error, cannot convert from int * to int or something like this, except for the main question

Will the compiler in the absence of stdlib.h consider malloc as a user-defined function and will not look for its declaration, and this will give some error related to the absence of delcaration / defination

+6
source share
2 answers

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

It also automatically and quietly β€œguesses” (outputs, infers) the types of function parameters from the types of arguments that you specified in your call. In your example, you indicated 20 , which would make the compiler guess that the unknown function malloc accepts a single parameter of type int . Note that this is also not true, since the real malloc accepts the size_t parameter.

In C99 and later, a function declaration is required. This means that forgetting to declare malloc (for example, forgetting to include <stdlib.h> ) is indeed an error that will lead to a diagnostic message. (However, the guessing behavior is still present in the language.)

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

+9
source

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

+4
source

Source: https://habr.com/ru/post/988750/


All Articles