Skip to main content

Tests

This document explains how to test an implementation of malloc provided as a shared library libmalloc.so.

Objective

This page explains how to:

  • Build the shared library libmalloc.so.
  • Run programs that use your allocator (linking and using LD_PRELOAD and LD_LIBRARY_PATH).
  • Debug programs that use your allocator with gdb.

Prerequisites

  • Compile the library with debug symbols (-g).

Build the shared library

Minimal example:

# build the shared library
gcc -Wall -Wextra -fPIC -shared -g -o libmalloc.so malloc.c

To explicitly link a binary against your local library:

gcc main.c -L. -lmalloc -o main
LD_LIBRARY_PATH=. ./main

-L. tells the linker to search the current directory for libraries, and -lmalloc links libmalloc.so.

Use LD_PRELOAD to override the system allocator

When you want to test your allocator with an existing program (without relinking), use LD_PRELOAD:

LD_PRELOAD=./libmalloc.so ls
LD_PRELOAD=./libmalloc.so ./my_program

LD_PRELOAD forces the dynamic loader to use symbols (malloc/free/realloc/calloc) from libmalloc.so instead of the system allocator.

Debugging with gdb

Important: gdb itself makes allocations. If you start gdb while LD_PRELOAD points at your allocator, gdb may load your allocator and become unstable if it is buggy. To avoid this, start gdb normally and set the environment for the debugged program from inside gdb.

Recommended workflow:

  1. Start gdb without LD_PRELOAD:
gdb ./main
  1. Inside gdb, set the environment that the inferior should use at startup and then run it:
(gdb) set env LD_LIBRARY_PATH .
(gdb) start

If you prefer LD_PRELOAD instead of LD_LIBRARY_PATH:

(gdb) set exec-wrapper env 'LD_PRELOAD=./libmalloc.so'
(gdb) start
info

Always compile with -g to get useful symbols.