fitzbutz
fitzbutz

Reputation: 976

Safest Way to Link Google's TCMalloc lib

After some days of test I figured out that the runtime patching mechanism patch_functions.cc is not safe to use in a production environment.
It seems to work well in a VS2010 project except for HeapAlloc() and HeapFree() but cannot be used in a VS2015 project due to some unresolved problems Open Issues. the windows readme describes this alternative way to use tcmalloc:


An alternative to all the above is to statically link your application with libc, and then replace its malloc with tcmalloc. This allows you to just build and link your program normally; the tcmalloc support comes in a post-processing step. This is more reliable than the above technique (which depends on run-time patching, which is inherently fragile), though more work to set up. For details, see https://groups.google.com/group/google-perftools/browse_thread/thread/41cd3710af85e57b


Unfortunately the provided lik is urechable, seems that google had closed the group.

Could someone explain me how to do this?

Upvotes: 0

Views: 1549

Answers (2)

OBones
OBones

Reputation: 319

I stumbled on this as well and believe I found a way to have it working.

First, in windows\config.h, you have to replace

#undef WIN32_OVERRIDE_ALLOCATORS 

by

#define WIN32_OVERRIDE_ALLOCATORS 

Then, and it's the most important thing, you have to make sure of two things:

  1. windows\patch_functions.cc is not compiled and linked
  2. windows\overridde_functions.cc is compiled and linked

At first, I omitted step 2 and got a barely functioning DLL where some memory allocations would get freed and overridden apparently at random.

In my case, making sure of both steps was just a matter of ensuring only windows\override_functions.cc is included in my libtcmalloc VS2017 project.

Upvotes: 0

Superlokkus
Superlokkus

Reputation: 5049

I assume it suggests to write your own malloc which uses tcmalloc.

So you have to define and link your own one (by creating or using an .c aka translation unit) and write something like this

#ifdef __cplusplus
extern "C" {
#endif

#include <stdlib.h>

void* malloc(size_t size) {
    return tcmalloc(size);
}

//Also define a free if memory which has been allocated by tcmalloc 
//needs to be freed by a special function
// Like 
/*
void free(void* ptr) {
    if (ptr) {
        tcfree(ptr);
    }
}
*/

#ifdef __cplusplus
}
#endif

Problem is: Depending on your building system or linker, it may nag about double symbols aka references. Then you have to somehow exclude libcs malloc, or change the libc by yourself.

Upvotes: 1

Related Questions