Obtaining and printing a memory map

Updated: October 26, 2022

Use the following sample code segment to obtain and then print the contents of a memory map:

#include <stdio.h>
#include <backtrace.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

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

    bt_accessor_t acc;
    bt_memmap_t memmap;

    if (bt_init_accessor(&acc, BT_SELF) == -1)
    {
        fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
                 "bt_init_accessor", errno, strerror(errno));
        return EXIT_FAILURE;
    }

    if (bt_load_memmap( &acc, &memmap) == -1)
    {
        fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
                 "bt_load_memmap", errno, strerror(errno));
        return EXIT_FAILURE;
    }

    if (bt_sprn_memmap(&memmap, out, sizeof(out)) == -1)
    {
        fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
                 "bt_sprn_memmap", errno, strerror(errno));
        return EXIT_FAILURE;
    }

    /* Make sure that the string is null-terminated. */
    out[sizeof(out) - 1] = '\0';
    puts(out);

    bt_unload_memmap( &memmap );

    if (bt_release_accessor(&acc) == -1)
    {
        fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
                 "bt_release_accessor", errno, strerror(errno));
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Additional notes about memory:

Note: There are no explicit links between the memory map and a backtrace. Consequently, you're responsible for ensuring that the memory map is reread to account for the proper handling of the removal of the dlopen() and dlclose() processes, as well as the recycling of process IDs.