Re: [glib] malloc and bdwgc

Am 08.01.2016 um 12:23 schrieb 张海:
Thank you very much for pointing me to __libc_* aliases.

However as I was trying to use bdwgc, I didn't figure out whether
bdwgc will infinite loop as I failed to identify the call to memory
allocation in its source :(

bdwgc itself has a --enable-redirect-malloc configure option, and by
greping the source with REDIRECT_MALLOC, I found that to correctly
redefine malloc and free one need to interfere with redefining dlopen,
threads and etc, and it seems quite hard to incorporate those lines of
code into my program. In this case I will need to end up building a
custom bdwgc with --enable-redirect-malloc.

I'm not sure. You don't have to touch any of the libraries you link if you implement malloc in the main program. If you define malloc() in a program, that *all* dynamically linked libraries should use the malloc() defined in the program. This is because, during dynamic link, unresolved references are resolved in load-order, and the main program is conceptually loaded first.

Thus, even the C library should call that, even if it provides malloc itself, because if global symbols are symbols are defined multiple times, the first symbol found is used (again, coming from the application).

The following example shows that the application's malloc is used even for memory allocated internally in the C library (here by asprintf()).
$ cat test.c
#include <stdlib.h>
#include <stdio.h>

extern void *__libc_malloc(size_t);
void *malloc(size_t n)
  return __libc_malloc(n);

int main()
  char *p = NULL;
  printf("%s\n", (asprintf(&p, "%s\n", "hello world"), p));

$ gcc test.c && ./a.out
hello world

PS: This should equally work if you use a third party library to implement malloc. However, in this case it's important that you link it first before any other libraries (especially before libc, but I think gcc does that by default).

Best regards

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]