Hack the standard function in library and call the native library function afterwards

后端 未结 3 1275
谎友^
谎友^ 2021-01-26 01:26

I am trying to hack the malloc function to call my malloc function first.Once my malloc function is executed within that, I want to invoke the standard malloc. But, I am getting

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 02:29

    The standard way I'm always using is creating a macro called MALLOC (or MYMALLOC or whatever) which does what you want. All occurrences of malloc I have to replace by the use of the macro, of course, and I can understand when this is not what you want.

    You also can achieve what you want by defining a macro called malloc (i. e. spelled like the original malloc) only when compiling the source you want to have your feature in. This malloc macro then would call a function called, say, wrappingMalloc which should be declared in a file which is compiled without defining the macro malloc and which then in turn can call the original function malloc. If this makefile fiddling is too much for you, you could also call the original function by calling (malloc) (this avoids running into the macro again):

        #include 
        #include 
    
        #define malloc(size) myMalloc(size)
    
        void *myMalloc(size_t size) {
          void *result;
          printf("mallocing %ld bytes", size);
          result = (malloc)(size);
          printf(" at %p\n", result);
          return result;
        }
    
        int main(int argc, char *argv[]) {
          char *buffer;
          buffer = malloc(10);
          return 0;
        }
    

    In C++ you might get along by overloading the new operator for your classes.

提交回复
热议问题