From b1e3a86776efab78b2f7ee879c5fed0093294bcd Mon Sep 17 00:00:00 2001 From: Scott Boggs Date: Sat, 13 Aug 2022 07:35:10 -0400 Subject: [PATCH] Fix null dereference when passing empty slice to Base64.encode (#12377) --- spec/std/base64_spec.cr | 6 ++++++ src/base64.cr | 1 + 2 files changed, 7 insertions(+) diff --git a/spec/std/base64_spec.cr b/spec/std/base64_spec.cr index 47c8c3665750..89e5d863825a 100644 --- a/spec/std/base64_spec.cr +++ b/spec/std/base64_spec.cr @@ -48,6 +48,12 @@ describe "Base64" do assert_prints base64_strict_encode(slice), "AQEBAQE=" end + it "encodes empty slice" do + slice = Bytes.empty + assert_prints base64_encode(slice), "" + assert_prints base64_strict_encode(slice), "" + end + it "encodes static array" do array = uninitialized StaticArray(UInt8, 5) (0...5).each { |i| array[i] = 1_u8 } diff --git a/src/base64.cr b/src/base64.cr index edd8813bd887..717d2e7de2ff 100644 --- a/src/base64.cr +++ b/src/base64.cr @@ -203,6 +203,7 @@ module Base64 bytes = chars.to_unsafe size = data.size cstr = data.to_unsafe + return if cstr.null? || size == 0 endcstr = cstr + size - size % 3 - 3 # process bunch of full triples