Compare commits

...

2 Commits

Author SHA1 Message Date
Thomas Lindner e412d63914 solve Challenge 5 of Set 1 2022-02-07 01:06:53 +01:00
Thomas Lindner 6abec1ca62 fix double free 2022-02-07 00:50:00 +01:00
4 changed files with 55 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 stdout = std.io.getStdOut().writer();
var bestplaintext = try allocator.alloc(u8, 0);
defer allocator.free(bestplaintext);
var bestplaintext = std.ArrayList(u8).init(allocator);
defer bestplaintext.deinit();
var bestscore: u32 = 0;
while (true) {
@ -58,9 +58,8 @@ pub fn main() anyerror!void {
decrypt(plaintext, ciphertext, key);
const s = score(plaintext);
if (s > bestscore) {
allocator.free(bestplaintext);
bestplaintext = try allocator.alloc(u8, plaintext.len);
std.mem.copy(u8, bestplaintext, plaintext);
try bestplaintext.resize(plaintext.len);
std.mem.copy(u8, bestplaintext.items, plaintext);
bestscore = s;
}
key +%= 1;
@ -70,5 +69,5 @@ pub fn main() anyerror!void {
}
}
try stdout.print("{s}\n", .{bestplaintext});
try stdout.print("{s}\n", .{bestplaintext.items});
}

View File

@ -0,0 +1,2 @@
Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal

View File

@ -0,0 +1,27 @@
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("challenge5_repeating_xor", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}

View File

@ -0,0 +1,21 @@
const std = @import("std");
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const stdin = std.io.bufferedReader(std.io.getStdIn().reader()).reader();
const stdout = std.io.getStdOut().writer();
const key = "ICE";
const input = try stdin.readAllAlloc(allocator, 4096);
defer allocator.free(input);
var i: usize = 0;
for (input) |*char| {
char.* ^= key[i];
i = (i + 1) % key.len;
}
try stdout.print("{s}\n", .{std.fmt.fmtSliceHexLower(input)});
}