I need to recode the free()
func for educational purpose and it must be named free()
also.
When i rename my function myfree()
it work flawlessly but when i name it free()
the program don't know if he need to use mine or the system's so the program just Segmentation fault(core dumped)
even if i don't call my free (just the declaration of another free()
func seem to crash it)
so how can i tell the compiler to use mine instead of the system's ?
thanks you in advance.
EDIT : Linux operating system
If you are looking for a standard way, I'm afraid it doesn't exist. Redefining standard library names is undefined behavior.
C11, 7.1.3.2:
In 7.1.4, there are is a long explanation of how the library may define a macro with the same name as the function and how to bypass that macro. There is no indication of how a user may override a standard library function.
You can also see this question for more information.
Non standard ways are of course always possible as you can find in other answers.
Basically, you have three options that I can see
#define
as @Mohamed suggests.If you're using GCC, you can use the compiler to help you. When you compile, include this on your link line:
-Xlinker --wrap=free
. This will redirect all calls tofree()
to use__wrap_free()
, which you must provide. If you wish to call the originalfree()
function, it's still there but renamed; you can call__real_free()
.This will capture pre-compiled libraries you link against, something a macro cannot do (but LD_PRELOAD can).
use macros for that: to force program to use your
myfree()
function:The easiest (not the safest) way is to
#define free myfree
so the preprocessor will replace all calls from free() to myfree(). Another, more safe approach, would be create a normal function called free() and do not include libraries, that also contain free() function.