How hamzahat/c_garbage_collector works
Project Type and Purpose
• Type: A C library providing a “safe” malloc/free wrapper–style garbage collector.
• Purpose:
– Track all memory allocations at runtime
– Offer three operations: ALLOCATE, FREE_ONE, FREE_ALL
– Automatically free leaked or untracked memory on failure or on demand
File Structure
• Top-level:
– ft_safe_malloc.c → contains implementation of:
· Internal tracker (likely a linked list or array of pointers)
· The ft_safe_malloc() API handling three keys
– README.md → describes usage, macro keys, and behavior
• No external configs, no frontend/backend split—this is purely a library component.
Core Components
1) Client Code
– Any C application that calls ft_safe_malloc() or malloc() directly.
2) ft_safe_malloc API Layer
– Exposed function: void *ft_safe_malloc(size_t size, int key, int exit_status, void *to_delete);
– Macro keys: ALLOCATE, FREE_ONE, FREE_ALL
3) Internal Tracker (Data Structure)
– Stores every successfully allocated pointer
– Supports insertion, lookup, deletion
4) Underlying Memory Allocator
– Standard malloc() and free() from <stdlib.h>
5) Exit Handler
– Invoked when allocation fails or when FREE_ALL is called with exit status
Relationships & Data Flow
• Client → ft_safe_malloc (API)
– Calls with key=ALLOCATE: API forwards to Underlying Allocator, then records pointer in Tracker
– Calls with key=FREE_ONE: API looks up pointer (if tracked), calls free(), removes from Tracker; if untracked, still calls free()
– Calls with key=FREE_ALL: API iterates Tracker, free() each pointer, optionally calls exit(exit_status)
• ft_safe_malloc (API) → Internal Tracker
– Insert/Delete/Iterate operations
• ft_safe_malloc (API) → Underlying Memory Allocator
– malloc(size) and free(ptr)
Architectural Patterns & Principles
• Wrapper Pattern: Encapsulates raw malloc/free calls in a safe API
• RAII-inspired Resource Tracking (though in C)
• Single Responsibility:
– API function orchestrates operations
– Tracker manages data structure
• Fail-Fast Strategy: On allocation failure, free all and exit