Overloading free() so my program use mine instead

2020-02-13 02:15发布

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

5条回答
Juvenile、少年°
2楼-- · 2020-02-13 02:45

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.

查看更多
地球回转人心会变
3楼-- · 2020-02-13 02:50

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.
查看更多
霸刀☆藐视天下
4楼-- · 2020-02-13 02:50

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).

查看更多
贪生不怕死
5楼-- · 2020-02-13 02:56

use macros for that: to force program to use your myfree() function:

#define free(X) myfree(X)
查看更多
不美不萌又怎样
6楼-- · 2020-02-13 02:58

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.

查看更多
登录 后发表回答