When I use malloc in a C program, I get a warning:
warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]
I can then include <malloc.h> or <stdlib.h> to get rid of the warning although it works without it as well.
So I was wondering, what’s the difference between these headers and which one does gcc links when I don’t include anything?
(I’m using ubuntu 12.04 64-bit with gcc 4.6.3)
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.hyou’ll find there some non-standard functions (e.g. malloc_stats(3), etc…) – in addition ofmalloc….And
gccdon’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
mallocyourself, which would be a bad idea),mallocis implicitly declared as returning someintvalue (which is wrong). I do invite you to pass at least the-Wallflag togccwhen using it.You might also pass
-vtogccto understand the actual programs involved:cc1is the compiler proper (producing assembly code),asthe assembler,ldthe linker, and collect2 an internal utility which invokes the linker.