Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether `malloc.h` is available in C?

malloc.h is a non-standard C header that declares extensions to the C standard library related to memory management. It is available on Linux.

I want my program to compile on many platforms but only use malloc.h functionality when it is available.

How can I check during compile time (via macros) whether the malloc.h library is available for my C program?

Edit: a solution could also go indirectly, such as checking the operating system, or anything else.

like image 343
shuhalo Avatar asked Dec 05 '25 14:12

shuhalo


2 Answers

You generate (autoconf, shell script creates a small c program etc) a header file, say, config.h, that only includes the header if is available. Optionally define a constant if you don't want to rely on what malloc.h defines:

#include <malloc.h>
#define MALLOC_H_FOUND 1

Then you code you include this header file and only perform actions based on a symbol found in malloc.h or the constant you defined above:

#include "config.h"

#ifdef _MALLOC_H // or MALLOC_H_FOUND
  // use malloc.c specific features
#else
 // fallback
#endif

via macros

It's not possible to check for header existence "via macros".

Typically, create a small valid program with #include <malloc.h> and try to compile that program. If the compilation is successful, means the header is available. Build systems are tools created exactly for that goal of automating such tasks, there are for example: CHECK_INCLUDE_FILE() in cmake, AC_CHECK_HEADER() in autoconf, conf.CheckCHeader in scons, cc.has_header in meson, etc.

Note: there is a gcc extension __has_include https://gcc.gnu.org/onlinedocs/cpp/_005f_005fhas_005finclude.html that is going into C23 https://en.cppreference.com/w/c/23 . If you aim only for gcc or only for C23, you can use #if __has_include(<malloc.h>).

like image 29
KamilCuk Avatar answered Dec 07 '25 06:12

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!