From cd30dcc2876a4d476ba26bb4874f382936a3401f Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sat, 19 Dec 2020 21:35:53 +0200 Subject: [PATCH] builtin: make array.ensure_cap/1 more robust --- vlib/builtin/array.v | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index a3844df3e3..c010cce441 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -91,15 +91,18 @@ fn (mut a array) ensure_cap(required int) { if required <= a.cap { return } - mut cap := if a.cap == 0 { 2 } else { a.cap * 2 } + mut cap := if a.cap > 0 { a.cap } else { 2 } for required > cap { cap *= 2 } - if a.cap == 0 { - a.data = vcalloc(cap * a.element_size) + new_size := cap * a.element_size + mut new_data := byteptr(0) + if a.cap > 0 { + new_data = v_realloc(a.data, new_size) } else { - a.data = v_realloc(a.data, cap * a.element_size) + new_data = vcalloc(new_size) } + a.data = new_data a.cap = cap }