From 2fafceab831e935e451a6ced29cdfa3bfa533b1b Mon Sep 17 00:00:00 2001 From: CJ van den Berg Date: Tue, 9 Apr 2024 18:12:22 +0200 Subject: [PATCH] fix: crash while rendering chunks longer than 4096 bytes (long lines) Proof that I was a Zig noob not too long ago. The defer of course runs immediately. --- src/tui/editor.zig | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/tui/editor.zig b/src/tui/editor.zig index 697c311..b744c76 100644 --- a/src/tui/editor.zig +++ b/src/tui/editor.zig @@ -593,13 +593,14 @@ pub const Editor = struct { const bufsize = 4095; var bufstatic: [bufsize:0]u8 = undefined; const len = leaf.buf.len; - var chunk: [:0]u8 = if (len > bufsize) - std.heap.c_allocator.allocSentinel(u8, len, 0) catch |e| return Buffer.Walker{ .err = e } - else - &bufstatic; - if (len > bufsize) { - defer std.heap.c_allocator.free(chunk); - } + var chunk_alloc: ?[:0]u8 = null; + var chunk: [:0]u8 = if (len > bufsize) ret: { + const ptr = self_.a.allocSentinel(u8, len, 0) catch |e| return Buffer.Walker{ .err = e }; + chunk_alloc = ptr; + break :ret ptr; + } else &bufstatic; + defer if (chunk_alloc) |p| self_.a.free(p); + @memcpy(chunk[0..leaf.buf.len], leaf.buf); chunk[leaf.buf.len] = 0; chunk.len = leaf.buf.len;