Skip to content

Commit 3d93c89

Browse files
daurnimatorandrewrk
authored andcommitted
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
1 parent 6756e54 commit 3d93c89

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

std/debug/failing_allocator.zig

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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;

0 commit comments

Comments
 (0)