Efficiently Managing Memory Cleanup in Functions with Multiple Allocations