views:

224

answers:

5

Possible Duplicate:
What is the best solution to replace a new memory allocator in an existing code?

I'm writing a library in C. I'd like to know if there is a way to divert every malloc() call my library makes to a different "augmented" testmalloc() function that I provide without (significantly) modifying my library. This question is inspired from p158 of Kernighan and Pike's "The Practice of Programming", where they say

Write a version of your storage allocator that intentionally fails early, to test your code for recovering from out-of-memory errors.

I am in a position where I could provide a wrapper mymalloc() and use that exclusively in my library. I suspect it will be necessary to use this freedom to avoid multiple symbol definitions during linking.

+2  A: 

yeah. you should include the library at last, and use #define malloc mymalloc

example:

library.h:

void * myalloc(int);
#define malloc myalloc

source.c:

#include <stdlib.h>
int* i = malloc(4);

-> uses myalloc

Yossarian
A problem with that is that a programmer would probably expect malloc to work, like, ahem, malloc. Wouldn't it be better to always use a function called myalloc, and define it as an alias to malloc in production case, but a completely different function in test cases ?
phtrivier
You can use #ifdef DEBUGGING or something to only redefine malloc when it is needed to. By default the redefintion shouldn't take place - no harm for the developer who isn't aware of the trick.
kgiannakakis
+1  A: 

in addition to Yossarian's answer, you can use malloc hooks, defined at least for the GNU C library.

dfa
hooking works in msvc too: http://msdn.microsoft.com/en-us/library/cy8c7wz5(VS.80).aspx ( but i didnt knew about it :] )
Yossarian
+2  A: 

I guess writing your own malloc:

char* malloc(size_t sz)
{
    return (char*)0;
}

and then linking it in doesn't work here?

(Background note: You can usually replace a function in a library with another by linking it in first in the link step. This doesn't replace the calls in the library, so the library still uses its own function, but everything that needed a link to malloc from your own code when the linker gets to your version will use your version.)

Mike D.
Its difficult to link only some functions from standard library .
Yossarian
+2  A: 

If you cannot modify the code you can consider using __malloc_hook. See (http://www.gnu.org/s/libc/manual/html_node/Hooks-for-Malloc.html)

corvus
A: 

It is even possible to write a malloc() implementation that can succeed or fail depending on a global. Unix linkers won't look for the real malloc function as it finds one in the object file(s). I do not know how this would behave on Windows.

void *malloc(size_t aSize)
{
  if (gNextMallocShallFail)
  {
     gNextMallocShallFail = 0;  //--- next call will succeed 
     return NULL;
  }
  else 
  {
    return realloc(NULL, aSize);
  }
}
philippe