r/C_Programming • u/icy-mist-01 • 28d ago
Article Wrote a lightweight Linux dynamic file descriptor leak detector project in C using LD_PRELOAD. Looking for critiques and reviews.
I've written an LD_PRELOAD file descriptor leak tracker in C.
https://github.com/anu-icon/libfdhunt
Apart from memory leaks which get the most spotlight, file descriptor leaks is a long-standing problem in production environments, often causing service crashes.
While Valgrind has --track-fds=yes, running full binary translation can be overkill or too slow if you're working with timing-sensitive code.
Polling lsof or /proc/$PID/fd also misses transient descriptors that open and vanish.
This is highly useful since you don't need advanced tools and extra permissions, don't have to recompile or review entire large code bases to find the flaw.
Just LD_PRELOAD=./build/libfdhunt.so /path/to/your/program [args]
How it works under the hood:
For anyone interested in the implementation:
Symbol Interposition: It uses dlsym(RTLD_NEXT, ...) to wrap standard libc syscall wrappers (open, close, pipe2, socket, dup2, epoll_create1, etc.).
O(1) Flat Array Registry: Instead of using linked lists or calling malloc/free inside hot syscall paths (which invites lock contention and heap re-entrancy issues), it uses a flat array indexed directly by descriptor number (table[fd]). It sizes the table on demand using sysconf(_SC_OPEN_MAX) and guards slot flips with a single mutex.
Exit Hook: Leak reporting is wired into GCC's __attribute__((destructor)). When the binary exits normally, the library sweeps the table, skips standard streams (0, 1, 2), and reports active descriptors.
Design constraints and comparison & prior art is in the readme
Looking forward to critique.
AI usage declaration: This is not vibe-coded. It evolved over a month starting from using linked lists to tackle a similar problem.
AI was used for cross checking, calibrating, testing, scaffolding and some documentation