Why include stdlib.h?

The C malloc () function is defined in stdlib.h. It should give an error if we do not include this file, but this code works fine with a little warning. My question is: if malloc () works without this header file, then why include it? Please clear my concepts.

# include <stdio.h> int main() { int a, b, *p; p = (int*)malloc(sizeof(int)*5); for(a=0;a<5;a++)p[a]=a*9; for(b=0;b<5;b++)printf("%d ",p[b]); } 
+4
source share
5 answers

In C, unfortunately, you do not need a preliminary declaration for functions. If the compiler encounters a new function, it will create an implicit declaration for it ("mmm`kay, this is how it is used, so I assume the type of the arguments ...").

Do not rely on this β€œfunction” and do not write code that compiles with warnings at all.

+10
source

Read the warning. He says that it is invalid. The compiler is just too kind to you. In Clang, this works, but it may not be in other compilers.

At least turn it on to suppress the warning. Unnecessary warnings are annoying. Any program should compile with warnings that are considered errors (I always include this).

+4
source

It looks like your compiler magic. Apart from the necessary headers, you can work with your compiler (which I assume is Microsoft), but it will not necessarily compile elsewhere (including future versions of the same compiler). Write a standard, portable code.

+3
source

Like many others, due to the fact that an error does not occur when there is no prototype for historical reasons. Previously, people often did not worry about prototyping functions, because pointers and integers were usually the same size, and integral types smaller than an integer were passed to an integer when passed as a parameter (and a floating point was rarely used for system programming).

If at some point they changed the compiler to give an error, if the function was not prototyped, then it would break many programs and would not be widely recognized.

With 64-bit addressing, we are now introducing a period when integers and pointers are not the same size, and programs are likely to break if you don't prototype functions like malloc () that return a pointer.

Gcc always sets the following options for your own programs: -Werror -Wstrict-prototypes

+2
source

stdlib.h is a general-purpose standard header that includes dynamic memory allocation functions and other standard functions.

For example, if you want to display a message at the end of your program, you will need to switch to the getch () function, this function reads a character from the keyboard, thereby giving the user time to read the displayed information.

The getch () function needs to include the stdlib header.

+2
source

All Articles