authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2019-05-05 23:17:23+10:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-05-11 09:55:41-04:00
log3d93c89fc55a428171bbfa779fb604801d84421d
tree3f01ec200b694e8facc4a27abc17998f3819f50a
parent6756e545f40dc7de373186a6581594e07bfd8200

std: the failing allocator didn't actually count allocations

Add a field '.allocations' to actually track the number of allocations. Additionally, only increment '.deallocations' when memory is freed

2 files changed, 14 insertions(+), 6 deletions(-)

std/debug/failing_allocator.zig+13-5
......@@ -10,6 +10,7 @@ pub const FailingAllocator = struct {
1010 internal_allocator: *mem.Allocator,
1111 allocated_bytes: usize,
1212 freed_bytes: usize,
13 allocations: usize,
1314 deallocations: usize,
1415
1516 pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator {
......@@ -19,6 +20,7 @@ pub const FailingAllocator = struct {
1920 .index = 0,
2021 .allocated_bytes = 0,
2122 .freed_bytes = 0,
23 .allocations = 0,
2224 .deallocations = 0,
2325 .allocator = mem.Allocator{
2426 .reallocFn = realloc,
......@@ -39,19 +41,25 @@ pub const FailingAllocator = struct {
3941 new_size,
4042 new_align,
4143 );
42 if (new_size <= old_mem.len) {
44 if (new_size < old_mem.len) {
4345 self.freed_bytes += old_mem.len - new_size;
44 } else {
46 if (new_size == 0)
47 self.deallocations += 1;
48 } else if (new_size > old_mem.len) {
4549 self.allocated_bytes += new_size - old_mem.len;
50 if (old_mem.len == 0)
51 self.allocations += 1;
4652 }
47 self.deallocations += 1;
4853 self.index += 1;
4954 return result;
5055 }
5156
5257 fn shrink(allocator: *mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
5358 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
54 self.freed_bytes += old_mem.len - new_size;
55 return self.internal_allocator.shrinkFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
59 const r = self.internal_allocator.shrinkFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
60 self.freed_bytes += old_mem.len - r.len;
61 if (new_size == 0)
62 self.deallocations += 1;
63 return r;
5664 }
5765};
std/zig/parser_test.zig+1-1
......@@ -2215,7 +2215,7 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
22152215 needed_alloc_count,
22162216 failing_allocator.allocated_bytes,
22172217 failing_allocator.freed_bytes,
2218 failing_allocator.index,
2218 failing_allocator.allocations,
22192219 failing_allocator.deallocations,
22202220 );
22212221 return error.MemoryLeakDetected;