From 9bb7e53e7f56fe3ddaa69849ff663ad18858e038 Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Thu, 12 Dec 2024 04:02:24 +0800 Subject: [PATCH] fixes #22153; UB calling allocCStringArray([""]) with --mm:refc (#24529) fixes #22153 It's a problem for refc because you cannot index a nil string: i.e. `[""]` is `{((NimStringDesc*) NIM_NIL)}` which cannot be indexed --- lib/system.nim | 2 +- tests/objects/t20972.nim | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index b2cf92ffb7..abfd1bcd41 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2143,7 +2143,7 @@ when not defined(js) and declared(alloc0) and declared(dealloc): let x = cast[ptr UncheckedArray[string]](a) for i in 0 .. a.high: result[i] = cast[cstring](alloc0(x[i].len+1)) - copyMem(result[i], addr(x[i][0]), x[i].len) + copyMem(result[i], x[i].cstring, x[i].len) proc deallocCStringArray*(a: cstringArray) = ## Frees a NULL terminated cstringArray. diff --git a/tests/objects/t20972.nim b/tests/objects/t20972.nim index 6383dc9b11..627357bc56 100644 --- a/tests/objects/t20972.nim +++ b/tests/objects/t20972.nim @@ -13,3 +13,11 @@ var info = ForkedEpochInfo(kind: true) doAssert info.kind info.kind = false doAssert not info.kind + +block: # bug #22153 + discard allocCStringArray([""]) + discard allocCStringArray(["1234"]) + + var s = "1245" + s.add "1" + discard allocCStringArray([s])