问题
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
回答1:
Basically, you have three options that I can see
- Redirect it during compile time, for example using
#define
as @Mohamed suggests. - Change it at runtime using LD_PRELOAD.
- Modify the existing malloc/free using malloc hooks.
回答2:
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 to free()
to use __wrap_free()
, which you must provide. If you wish to call the original free()
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).
回答3:
use macros for that: to force program to use your myfree()
function:
#define free(X) myfree(X)
回答4:
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.
回答5:
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:
... If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.
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.
来源:https://stackoverflow.com/questions/14727814/overloading-free-so-my-program-use-mine-instead-of-the-systems