From e7856a1afcf9d6da73881f764eb714f997234f52 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Mon, 16 Dec 2019 21:29:32 +0300 Subject: [PATCH] do not allow malloc(0) --- vlib/builtin/builtin.v | 2 +- vlib/builtin/string.v | 3 +++ vlib/encoding/base64/base64.v | 12 ++++++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) 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)) }