简体   繁体   中英

Why do we include stdlib.h?

C function malloc() is defined under stdlib.h .

It should give an error if we don't include this file, but this code works fine with a little warning.

My question is, if malloc() works without this header file, then why do we need to include it? Please help clarify 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]); 
}

In C unfortunately you don't need pre-declaration for functions. If the compiler encounters with a new function it will create an implicit declaration for it ("mmm`kay, this how it is used so I will assume that the type of the arguments are..").

Do not rely on this "feature" and in general do not write code that compiles with warnings.

Read the warning. It says it's invalid. The compiler is simply too kind to you. In Clang this works, but it might not in other compilers.

At least include it to suppress the warning. Unnecessary warnings are annoying. Any program should compile with warnings treated as errors (I always enable that).

It appears that that's your compiler's magic. Not including the necessary headers may work on your compiler (which I suppose is by Microsoft), but it won't necessarily compile elsewhere(that includes future versions of the same compiler). Write standard-conforming, portable code.

stdlib.h is of the general purpose standard header which includes functions of Dynamic Memory allocation and other Standard Functions.

For example if you want to display a message at the end of the execution of your program you will need to go for the getch() function,this functions reads a character from keyboard thus giving user the time to read the displayed Information.

The getch() function requires the stdlib header to be Included.

Like many things in c the reason that an error isn't generated when there is no prototype is for historical reasons. In the early days people often didn't bother prototyping functions because pointers and integers were usually the same size and integral types smaller than an integer were promoted to an integer when passed as a parameter (and floating point was rarely used for systems programming).

If at any point they had changed the compiler to give an error if a function was not prototyped then it would have broken many programs and would not have gained widespread acceptance.

With 64 bit addressing we are now entering a period when integers and pointers are not the same size and programs will most likely break if you do not prototype functions like malloc() that return a pointer.

In gcc always set the following options for your own programs: -Werror -Wstrict-prototypes

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