tags:

views:

107

answers:

3

I am reading source code of hoard memory allocator, and in the file of gnuwrapper.cpp, there are the following code

#define CUSTOM_MALLOC(x)     CUSTOM_PREFIX(malloc)(x)  

What's the meaning of CUSTOM_PREFIX(malloc)(x)? is CUSTOM_PREFIX a function? But as a function it didn't defined anywhere. If it's variable, then how can we use variable like var(malloc)(x)?

more code:

#ifndef __GNUC__
#error "This file requires the GNU compiler."
#endif

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>


#ifndef CUSTOM_PREFIX   ==> here looks like it's a variable, so if it doesn't define, then define here.
#define CUSTOM_PREFIX
#endif

#define CUSTOM_MALLOC(x)     CUSTOM_PREFIX(malloc)(x)    ===> what's the meaning of this?
#define CUSTOM_FREE(x)       CUSTOM_PREFIX(free)(x)
#define CUSTOM_REALLOC(x,y)  CUSTOM_PREFIX(realloc)(x,y)
#define CUSTOM_MEMALIGN(x,y) CUSTOM_PREFIX(memalign)(x,y)
+6  A: 

In your code, since CUSTOM_PREFIX is defined to be nothing, the string CUSTOM_PREFIX(malloc)(x) will expand to

(malloc)(x)

which is equivalent to the usual

malloc(x)

However, the CUSTOM_PREFIX allows the developer to choose a different memory management function. For example, if we define

#define CUSTOM_PREFIX(f) my_##f

then CUSTOM_PREFIX(malloc)(x) will be expanded to

my_malloc(x)
KennyTM
actually, `(malloc)(x)` is not equivalent to `malloc(x)`: the former is guaranteed to be a function call, whereas the latter might be a macro invocation (see C99 7.1.4 §5 for an example showing the different ways to invoke standard lib functions)
Christoph
A: 

CUSTOM_PREFIX is defined as nothing, so it will just disappear, leaving behind (malloc)(x), which is the same as malloc(x). Why? I don't know. Perhaps other places in the code set CUSTOM_PREFIX to something else.

Marcelo Cantos
A: 

At a guess, its a macro which changes calls to malloc(x) etc. into something like:

DEBUG_malloc( x );

You can choose to supply the macro yourself, to provide a customised prefix for the functions, or not in which case the names won't be changed.

anon