How properly Append U8

move the:

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

from the editorRefreshScreen function to the beginning of main, all other functions that need an allocator need to take allocator as a std.mem.Allocator parameter.


You shouldn’t create separate allocator instances all over the place, normally you create the gpa in main and then pass the allocator-interface to functions that need it, then some parts of the program may use it to create a different allocator, that is just needed temporarily.

If you create separate allocators without having a good reason for it, it defeats the debugging features of the gpa, by not being sure anymore if your allocator was even de-initialized at all. By just using one, that is de-initialized in main, you can be sure it detects the leaks once the program shuts down, it also makes it easier to change what allocator is used if you eventually want to change it.


As @IntegratedQuantum has already pointed out it would be simpler to readFileAlloc the entire file, and then find the lines within that.

Additionally you don’t need to concatenate all the lines before outputting them,
instead you can define a buffered writer and directly write the lines to it,
then flush the buffered writer to make sure everything is written.

Without a buffered writer you risk making more system calls (which your code avoids by concatenating first, but that itself creates unnecessary reallocations, when the goal is to output the result, writing the lines to a buffered writer is more efficient, because it means your program doesn’t have to allocate and re-allocate a growing buffer)
(So something more like this String formatting in a bit more complex cases - #10 by plano)

1 Like