fix double free

master
Thomas Lindner 2022-02-07 00:50:00 +01:00
parent 55283f4376
commit 6abec1ca62
1 changed files with 5 additions and 6 deletions

View File

@ -43,8 +43,8 @@ pub fn main() anyerror!void {
const stdin = std.io.bufferedReader(std.io.getStdIn().reader()).reader(); const stdin = std.io.bufferedReader(std.io.getStdIn().reader()).reader();
const stdout = std.io.getStdOut().writer(); const stdout = std.io.getStdOut().writer();
var bestplaintext = try allocator.alloc(u8, 0); var bestplaintext = std.ArrayList(u8).init(allocator);
defer allocator.free(bestplaintext); defer bestplaintext.deinit();
var bestscore: u32 = 0; var bestscore: u32 = 0;
while (true) { while (true) {
@ -58,9 +58,8 @@ pub fn main() anyerror!void {
decrypt(plaintext, ciphertext, key); decrypt(plaintext, ciphertext, key);
const s = score(plaintext); const s = score(plaintext);
if (s > bestscore) { if (s > bestscore) {
allocator.free(bestplaintext); try bestplaintext.resize(plaintext.len);
bestplaintext = try allocator.alloc(u8, plaintext.len); std.mem.copy(u8, bestplaintext.items, plaintext);
std.mem.copy(u8, bestplaintext, plaintext);
bestscore = s; bestscore = s;
} }
key +%= 1; key +%= 1;
@ -70,5 +69,5 @@ pub fn main() anyerror!void {
} }
} }
try stdout.print("{s}\n", .{bestplaintext}); try stdout.print("{s}\n", .{bestplaintext.items});
} }