Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to redefine malloc at link time on Windows?

Tags:

c

windows

I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:

MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj)

This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?

I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.

like image 276
Jazz Avatar asked Sep 23 '08 12:09

Jazz


3 Answers

There is really good discussion of how hard this is here:

http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/

Apparently, you need to patch the CRT

Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT

"he also mentions that if you link your malloc as a lib before the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems."

like image 67
Lou Franco Avatar answered Sep 22 '22 11:09

Lou Franco


I think it depends in which order you link the files. I think you need to link your custom function first, then the import library.

like image 31
dguaraglia Avatar answered Sep 21 '22 11:09

dguaraglia


From version 3.0 Firefox uses a custom allocator (AFAIR jmalloc) -- you could check how they did it. I read that they had some problems with it. You may check this blog post.

like image 29
Kasprzol Avatar answered Sep 19 '22 11:09

Kasprzol