// glibc's malloc a step at a time, for `ztrace record --heap -b heap_step`: each // call of `heap_step` follows one change to the heap. Seventeen chunks of one // size fill its tcache bin (7 before glibc 2.42, 16 by default since) and // pass the rest on, to a fastbin where there are fastbins; a chunk too large // for the tcache, freed beside one in use, goes to the unsorted bin; a // larger request sorts it into a large bin (2.40 consolidates the fastbins // first) and is served from the top, to which it returns when freed. #include // Volatile, or the compiler proves the allocations away. static void *volatile small[17], *volatile big, *volatile guard, *volatile larger; __attribute__((noinline)) void heap_step(int n) { __asm__ volatile("" : : "r"(n) : "memory"); } int main(void) { for (int i = 0; i < 17; i++) small[i] = malloc(0x28); big = malloc(0x500); guard = malloc(0x18); heap_step(1); for (int i = 0; i < 17; i++) free(small[i]); heap_step(2); free(big); heap_step(3); larger = malloc(0x1000); heap_step(4); free(larger); heap_step(5); return 0; }