Does mtrace() still work in modern distros?

tldr: Does mtrace still work or am I just doing it wrong?

I was attempting to use mtrace and have been unable to get it to write data to a file. I followed the instructions in man 3 mtrace:

t_mtrace.c:

#include <mcheck.h>
#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
    mtrace();

    for (int j = 0; j < 2; j++)
        malloc(100);            /* Never freed--a memory leak */

    calloc(16, 16);             /* Never freed--a memory leak */
    exit(EXIT_SUCCESS);
}

Then running this in bash:

gcc -g t_mtrace.c -O0 -o t_mtrace
export MALLOC_TRACE=/tmp/t
./t_mtrace
mtrace ./t_mtrace $MALLOC_TRACE

but the file /tmp/t (or any other file I attempt to use) is not created. When I create an empty file with that name it remains zero length. I’ve tried using relative paths in the MALLOC_TRACE. I tried adding setenv("MALLOC_TRACE", "/tmp/t", 1); inside the program before the mtrace() call. I’ve tried adding muntrace() before the program terminates. I’ve tried these tactics on Ubuntu 22.04 and Fedora 39, and I get the same result: the trace file is empty. The ctime and mtime on the file (if I create it in advance) are unchanged when I run the program. I’ve verified the permissions of the file and its parent directory are read/writable. strace isn’t showing that the file in question is stated, much less opened.

This occurs using Glibc 2.35 on Ubuntu and 2.38 on Fedora.

This isn’t a question on how to profile or check for memory leaks. I realize I can do this with valgrind or half a dozen other programs, this is mostly a curiosity and me wanting to know if this is a bug that might need to be patched or whether the man page needs updating (or whether I’m just misapprehending something and the only problem is sitting in my chair).

Asked By: TopherIsSwell

||

mtrace still works, but the man page is outdated. The reference documentation explains how to use it:

LD_PRELOAD=/usr/lib64/libc_malloc_debug.so.0 MALLOC_TRACE=/tmp/t ./t_mtrace

(replace with the appropriate path to libc_malloc_debug.so on your system — the above is appropriate for Fedora and derivatives on 64-bit x86; on Debian derivatives, use LD_PRELOAD=/lib/$(gcc -print-multiarch)/libc_malloc_debug.so.0).

In version 2.34 of the GNU C library, memory allocation debugging was moved to a separate library, which must be pre-loaded when debugging is desired.

Answered By: Stephen Kitt
Categories: Answers Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.