
C question : redefining a new malloc() calling standard malloc()
Quote:
>Thanks for this first response,
>but I have to precise my problem a little.
>I also want other library functions (for instance, C++ new()) to call my
>redefined function malloc() and not the standard library one.
What you are asking for is not possible in the C language, and the C++ bit is
entirely beyond the scope.
The external names claimed by the C library are reserved for use as external
names. A strictly conforming C program may not write its own version of
a library function.
Under many compilers, however, it is possible to easily overrride a library
function and, for instance, write your own malloc that will be linked to
by not only your program but any libraries that it uses. If, on that platform,
C++ implements new and delete using calls to malloc, they can be overriden
too.
Quote:
>So, I must have a function malloc() to create a symbol for link ! Not
>just a #define that only my code can see...
>Localy, I have two solutions :
>* make a copy of the standard library and change the symbol name from
>malloc to Malloc and call Malloc() in my real_malloc() function. This is
>not very portable but can be useful for testing purpose.
What you are asking for can't be really be made portable anyway.
Quote:
>* get source code from malloc (for instance :
>http://g.oswego.edu/dl/html/malloc.html) and adapt it to my problem
>case. This is not very good since I would like to be able to call the
>native malloc(). But it also works.
>Any suggestions ???
In Linux, for instance, you would just write your function and call it malloc.
To call the ``native'' malloc, you would refer to it as __libc_malloc or
something like that, if I recall correctly.
Quote:
>Xavier.
>> > * my_malloc.h : my redefinition of malloc()
>> > -------------
>> > #include <stdlib.h>
>> > void* malloc(size_t);
Right there, the program invokes undefined behavior on two counts. First of
all, when you #include a standard header into your translation units, the
identifiers exported by that header are completely off limits for any purpose.
The <stdlib.h> header could easily #define a macro called malloc, which would
make a mess of your subsequent declaration. But don't think that you can
just do an #undef malloc and be off the hook.
Secondly, if you are going to write your own malloc, you must not include the
<stdlib.h> header, and to remain strictly conforming, you must declare it
static because even if you don't include the header, the name malloc is still
reserved for external linkage.