difference between <stdlib.h> and <malloc.h>

Solution 1:

The <malloc.h> header is deprecated (and quite Linux specific, on which it defines non-standard functions like mallinfo(3)). Use <stdlib.h> instead if you simply need malloc(3) and related standard functions (e.g. free, calloc, realloc ....). Notice that <stdlib.h> is defined by C89 (and later) standards, but not <malloc.h>

Look into /usr/include/malloc.h you'll find there some non-standard functions (e.g. malloc_stats(3), etc...) - in addition of malloc....

And gcc don't link header files, but libraries. Read Levine's book about linkers & loaders for more.

If you don't include any headers (and dont explicitly declare malloc yourself, which would be a bad idea), malloc is implicitly declared as returning some int value (which is wrong). I do invite you to pass at least the -Wall flag to gcc when using it.

You might also pass -v to gcc to understand the actual programs involved: cc1 is the compiler proper (producing assembly code), as the assembler, ld the linker, and collect2 an internal utility which invokes the linker.

Solution 2:

stdlib.h is a standard C header that declares among other things the malloc(), calloc(), free() functions. This is the header you should include.

malloc.h is a non-standard header, found on many systems where it often defines additional functions specific to the malloc implementation used by that platform.

If you do not include any of these, there's no default, however if you call malloc() without a prior declaration of the malloc function, C will assume the function prototype is int malloc();, which is often wrong. In addition to the headers, C compilers typically link to a standard library, e.g. glibc on Linux, where the implementation of malloc resides.

Note that there's a difference between header files and libraries. Header files declare things, like structs and function prototypes. Libraries contain the implementation, the compiled code. You link to library, and you #include header files.

Solution 3:

The headers declare different sets of functions, but both forward-declare malloc.

If you don't include either of them then you don't have a prototype for malloc, hence the warning. But you link against the same function regardless, because there is only one malloc function. It's just forward-declared in two places. The forward-declarations aren't there to help link against the malloc function, they're there so that the compiler can emit the correct code around the call, to specify the arguments and read the return value.

Note that <malloc.h> is not a standard include. I don't think stdlib.h ever includes malloc.h on GCC, but you can imagine that it might since that's one way to provide the necessary declaration.