diff --git a/vlib/builtin/builtin.v b/vlib/builtin/builtin.v index 919c86e35e..8bc049bcf8 100644 --- a/vlib/builtin/builtin.v +++ b/vlib/builtin/builtin.v @@ -105,7 +105,7 @@ __global nr_mallocs int = 0 [unsafe_fn] pub fn malloc(n int) byteptr { - if n < 0 { + if n <= 0 { panic('malloc(<0)') } $if prealloc { diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 17886c8411..d235d12afe 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1126,6 +1126,9 @@ pub fn (s []string) join_lines() string { // reverse will return a new reversed string. pub fn (s string) reverse() string { + if s.len == 0 { + return '' + } mut res := string { len: s.len str: malloc(s.len) diff --git a/vlib/encoding/base64/base64.v b/vlib/encoding/base64/base64.v index f708f267d9..08208b3a1e 100644 --- a/vlib/encoding/base64/base64.v +++ b/vlib/encoding/base64/base64.v @@ -24,7 +24,11 @@ const ( * NB: if you need to decode many strings repeatedly, take a look at decode_in_buffer too. */ pub fn decode(data string) string { - buffer := malloc( data.len * 3 / 4 ) + size := data.len * 3 / 4 + if size <= 0 { + return '' + } + buffer := malloc(size) return tos(buffer, decode_in_buffer(data, buffer) ) } @@ -36,7 +40,11 @@ pub fn decode(data string) string { * NB: if you need to encode many strings repeatedly, take a look at encode_in_buffer too. */ pub fn encode(data string) string { - buffer := malloc( 4 * ((data.len + 2) / 3) ) + size := 4 * ((data.len + 2) / 3) + if size <= 0 { + return '' + } + buffer := malloc(size) return tos(buffer, encode_in_buffer(data, buffer)) }