From 722a2c71c3549fa64a1625ebd940c3633d61814e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kr=C3=BCger?= <45282134+UweKrueger@users.noreply.github.com> Date: Thu, 7 May 2020 22:41:41 +0200 Subject: [PATCH] builtin: new_array: cap should not be less than len --- vlib/builtin/array.v | 6 +++--- vlib/builtin/builtin.v | 7 +++++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 803409caa0..d83da8d1ce 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -17,7 +17,7 @@ pub mut: // Internal function, used by V (`nums := []int`) fn __new_array(mylen int, cap int, elm_size int) array { - cap_ := if cap == 0 { 1 } else { cap } + cap_ := if cap < mylen { mylen } else { cap } arr := array{ len: mylen cap: cap_ @@ -29,11 +29,11 @@ fn __new_array(mylen int, cap int, elm_size int) array { // Private function, used by V (`nums := [1, 2, 3]`) fn new_array_from_c_array(len, cap, elm_size int, c_array voidptr) array { - cap_ := if cap == 0 { 1 } else { cap } + cap_ := if cap < len { len } else { cap } arr := array{ len: len - cap: cap + cap: cap_ element_size: elm_size data: vcalloc(cap_ * elm_size) } diff --git a/vlib/builtin/builtin.v b/vlib/builtin/builtin.v index ca9b33f07f..032e22e1b3 100644 --- a/vlib/builtin/builtin.v +++ b/vlib/builtin/builtin.v @@ -142,10 +142,13 @@ pub fn v_calloc(n int) byteptr { } pub fn vcalloc(n int) byteptr { - if n <= 0 { + if n < 0 { panic('calloc(<=0)') + } else if n == 0 { + return byteptr(0) + } else { + return C.calloc(n, 1) } - return C.calloc(n, 1) } [unsafe_fn]