0

Just out of curiosity, how to redefine a standard library function, such as free to be something else? Something like:

delete_function free;
void free() {
    printf("I'm free!");
}
Neo
  • 1,031
  • 2
  • 11
  • 27
  • 1
    https://stackoverflow.com/questions/262439/create-a-wrapper-function-for-malloc-and-free-in-c – Alexander Dmitriev Aug 11 '20 at 09:39
  • Formally you aren't allowed to use identifiers present in the standard libs. In practice, you can "mock" standard functions by using function-like macros, but it's not recommended. – Lundin Aug 11 '20 at 11:03
  • 1
    FYI, search for “interpose” or “interposition.” This refers to inserting a new function in place of an existing function while still being able to call the original function—e.g., cause all calls to `free` to call a custom version that prints or records information and then calls the actual `free` in the standard library. That may be more than you want (although people asking about replacing `free` often want this), but it is also sufficient for what you want. – Eric Postpischil Aug 11 '20 at 11:08

2 Answers2

2

Within pure C, you can't. If you really want to, look at your linker documentation, but your are more likely to find what you are looking for in an instrumentation toolkit like valgrind.

user1937198
  • 4,987
  • 4
  • 20
  • 31
1

There is no way to redefine a function that you have already defined. C simply does not support that.

What you can do is to skip including stdlib.h and write your own replacement. However, be aware that it might have unexpected implications to do so, since those identifiers are reserved in the standard.

It's possible to use the preprocessor. Maybe there are some good use for it, but I'd say it's probably better to avoid it. But it does work. Here is an example:

#include <stdio.h>

void foo() 
{
    puts("foo");
}

#define foo() do { foo_replacement(); } while(0)

void foo_replacement() 
{
    puts("foo_replacement");
}

int main()
{
    foo();
}

Output:

$ ./a.out 
foo_replacement
klutt
  • 30,332
  • 17
  • 55
  • 95
  • Re “What you can do is to skip including `stdlib.h` and write your own replacement”: The behavior of providing your own “replacement” for a standard library function is not defined by the C standard, per C 7.1.3 1: “All identifiers with external linkage in any of the following subclauses (including the future library directions) and `errno` are always reserved for use as identifiers with external linkage.” Compilers may “know” what a standard library function does and modify (optimize) the code accordingly, such as replacing a short constant-length `memcpy` with inline code, and so on. – Eric Postpischil Aug 11 '20 at 11:11
  • Compilers may have a switch to disable that behavior, but it is compiler-dependent. It is not safe to advise people they can write their own replacements to standard library functions without taking steps to be sure. – Eric Postpischil Aug 11 '20 at 11:12