Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

gcc

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)

like image 315
none Avatar asked Oct 19 '12 11:10

none


People also ask

Is malloc in Stdlib H?

In computing, malloc is a subroutine for performing dynamic memory allocation. malloc is part of the standard library and is declared in the stdlib. h header. Many implementations of malloc are available, each of which performs differently depending on the computing hardware and how a program is written.

What is Stdlib H used for?

The header file stdlib. h stands for Standard Library. It has the information of memory allocation/freeing functions.

What is the difference between Stdio H and Stdlib H?

One easy way to differentiate these two header files is that “<stdio. h>” contains declaration of printf() and scanf() while “<stdlib. h>” contains declaration of malloc() and free(). In that sense, the main difference in these two header files can considered that, while “<stdio.

Why #include Stdlib H is used in C?

h is the header of the general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversions and others. It is compatible with C++ and is known as cstdlib in C++. The name "stdlib" stands for "standard library".


1 Answers

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.

like image 91
Basile Starynkevitch Avatar answered Oct 03 '22 21:10

Basile Starynkevitch