• Uncategorized

About c : Unable-to-track-free-calls-for-printf

Question Detail

I’m writing are small memory profiler which is using the LD_PRELOAD trick. Overall it works good for malloc and free. Unfortunately I’m not able to track IO-Operations such as printf. Those functions get tracked correctly at the malloc functions but it didn’t seam that they got passed to free. Here are code snippets:

void heaptracker_init(void) 
{
    ignore = false;

    // get original symbols
    libc_hooks.malloc = dlsym(RTLD_NEXT, "malloc");
    check_error_dlfcn(libc_hooks.malloc);

    // for the other primitives as well ...

    // init list for storing information
    if ((alloc_list = list_init()) == NULL)
        return;
    
// does write results from list
    if (atexit(heaptracker_destroy))
        return;

    initialized = true;
    
    stopped = true;

    // for concurrent access on list ...
    if ((errno = pthread_mutex_init(&mutex, NULL)) != 0) {
        return;
    }

    stopped = false;
}

The malloc routine does store the allocations in a list and performs the actual allocation.

void *malloc(size_t size) 
{
   if (!initialized)
        heaptracker_init();

    void * (*libc_malloc)(size_t) = libc_hooks.malloc;

    void *p = libc_malloc(size);

    list_append(alloc_list, infos, p, size, stacktrace_length);
    return p;
}

The free routine looks like this:

void free(void *ptr)
{

if (!initialized)
        heaptracker_init();


    if (pthread_mutex_lock(&mutex) != 0) 
        return;

    // does remove
    list_remove(alloc_list, ptr);    
    
    errno = pthread_mutex_unlock(&mutex);
    libc_hooks.free(ptr);
}

For a small test programm like this one:

int main()
{
    printf("Hello World");
    char *buffer = malloc(100);
    return 0;
}

The expected output should be:

{
"type": "leak",
"bytes": 100,
"stacktrace": ["main"]
}

While the actual output is:

[
   {
    "type": "leak",
    "bytes": 100,
    "stacktrace": ["main"]
    },
    {
     "type": "leak",
     "bytes": 1024,
     "stacktrace": ["main", "_IO_printf", ...,  "_IO_file_doallocate"]
     }
]

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.