Regarding headers

malloc is defined in <stdlib.h> right .But even without #include <stdlib.h> its working. Is #include similar to import in python where we import and use functions in it.

This is an interesting question.

First, your compiler should give you a warning, something like “implicit declaration of function malloc” and you’ll be better of if you don’t ignore it.

Now, I won’t pretend I know for sure what’s going on, but here’s how I understand it:

malloc is not defined in stdlib.h, it’s declared there. That means the compiler can derive information about the types of its arguments and return values from the information in that header, but it doesn’t need that declaration to find the actual function because it resides somewhere deep in the C implementation.

Althoug things can happen to work without the declaration, it is still crucial for all the parts of your program to work together. malloc returns pointers and pointers are really just numbers like everything else. You have to make sure that the compiler assumes the right sizes for all the chunks of memory you’re passing around, and that information is in the declaration. You’re probably just lucky because on your system standard integer sizes and pointer sizes match. But don’t rely on that, and certainly don’t assume that it will work the same on every other system.

My compiler expects just one #include header. If i include stdio.h it works fine or stdlib.h it works fine. Atleast one #include should be present. If no header is typed then I get Error.

incompatible implicit declaration of built-in function ‘exit’

I guess malloc is needed for some functions that are declared in stdio.h, so stdio.h includes stdlib.h automatically.

A free service run by Zed A. Shaw for