![Quote](https://cboard.cprogramming.com/images/misc/quote_icon.png)
Originally Posted by
MutantJohn
Well, I guess you can run out of available memory but can malloc fail in any other case?
Yes. Most operating systems can impose per-process limits the processes are not allowed to exceed, even if there is technically more memory available. For example, in Linux these can be queried using getrlimit().
![Quote](https://cboard.cprogramming.com/images/misc/quote_icon.png)
Originally Posted by
MutantJohn
They claim the command to use it is "LD_PRELOAD=/path/libhoard.so" but how do I actually check if Hoard's libraries are being used instead of the standard malloc one?
Using the dynamic linker (include <dlfcn.h>, and link using -ldl). For example:
Code:
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#ifndef LIBC_NAME
#define LIBC_NAME "libc.so.6"
#endif
#ifndef LIBHOARD_NAME
#define LIBHOARD_NAME "libhoard.so"
#endif
int main(void)
{
void *libhoard_handle, *libhoard_malloc;
void *libc_handle, *libc_malloc;
void *current_malloc;
libc_handle = dlopen(LIBC_NAME, RTLD_NOW | RTLD_NOLOAD | RTLD_GLOBAL);
if (!libc_handle) {
fprintf(stderr, "%s\n", dlerror());
return 1;
}
current_malloc = dlsym(RTLD_DEFAULT, "malloc");
libc_malloc = dlsym(libc_handle, "malloc");
if (current_malloc == libc_malloc) {
fprintf(stderr, "malloc() is from standard C library (%s)\n", LIBC_NAME);
} else {
libhoard_handle = dlopen(LIBHOARD_NAME, RTLD_NOW | RTLD_NOLOAD | RTLD_GLOBAL);
if (libhoard_handle) {
libhoard_malloc = dlsym(libhoard_handle, "malloc");
if (current_malloc == libhoard_malloc) {
fprintf(stderr, "malloc() is from Hoard library (%s)\n", LIBHOARD_NAME);
} else {
fprintf(stderr, "malloc() is from an unknown library.\n");
}
dlclose(libhoard_handle);
} else {
fprintf(stderr, "%s: Hoard library not loaded.\n", LIBHOARD_NAME);
}
}
dlclose(libc_handle);
return 0;
}
But really, you normally just want to know if the Hoard library is loaded or not. Here is a simple function, library_loaded(), that will return nonzero if the named library (say, "libhoard.so" or "libc.so.6") is loaded, zero if not loaded.
Code:
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
int library_loaded(const char *const name)
{
void *handle;
int retval;
if (!name || !*name)
return 0;
handle = dlopen(name, RTLD_NOW | RTLD_NOLOAD | RTLD_GLOBAL);
if (handle != NULL) {
retval = 1;
dlclose(handle);
} else
retval = 0;
return retval;
}
int main(int argc, char *argv[])
{
int arg;
if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
fprintf(stderr, "\nUsage: %s LIBRARY ...\n\n", argv[0]);
return 1;
}
for (arg = 1; arg < argc; arg++)
if (library_loaded(argv[arg]))
printf("%s: Loaded\n", argv[arg]);
else
printf("%s: Not loaded\n", argv[arg]);
return 0;
}
If you save the above as libtest.c, you can compile and run it using
Code:
gcc -W -Wall libtest.c -ldl -o libtest
./libtest libc.so.6 libhoard.so
env LD_PRELOAD=/path/libhoard.so ./libtest libc.so.6 libhoard.so