Compiling a custom malloc

后端 未结 3 1010
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 23:31

I have written a custom library which implements malloc/calloc/realloc/free using the standard C prototypes, and I figured out how to compile it to an so. I want to test the

3条回答
  •  囚心锁ツ
    2021-01-12 23:53

    If you have control of the source code that is to use this library, here is one possibility. Use different function names: Rather than malloc, for example, call it newCoolMalloc. This method is sometimes simpler and doesn't depend on special linker options.

    Then in your code, use #define to cause the code to call the desired set of functions. You can #define malloc to be something different. For example:

    #define malloc newCoolMalloc
    #define free   newCoolFree
    

    If you do that, though, you have to be very very careful to include that consistently. Otherwise you run the risk of using stdlib malloc in one place and then your own free in another leading to messy bugs. One way to help mitigate that situation is to (if possible) in your own code use custom names for the allocation and free functions. Then it is easier to ensure that the correct one is being called. You can define the various custom names to your own malloc functions or even the original stdlib malloc functions.

    For example, you might use mallocPlaceHolder as the actual name in the code:

    someThing = mallocPlaceHolder( nbytes );
    

    Then your defines would look more like this:

    #define mallocPlaceHolder myCoolMalloc
    

    If no function of the form mallocPlaceHolder (and associated free) actually exist, it avoids mixing different libraries.

提交回复
热议问题