do not allow malloc(0)

pull/3119/head
Alexander Medvednikov 2019-12-16 21:29:32 +03:00
parent 10718557a2
commit e7856a1afc
3 changed files with 14 additions and 3 deletions

View File

@ -105,7 +105,7 @@ __global nr_mallocs int = 0
[unsafe_fn] [unsafe_fn]
pub fn malloc(n int) byteptr { pub fn malloc(n int) byteptr {
if n < 0 { if n <= 0 {
panic('malloc(<0)') panic('malloc(<0)')
} }
$if prealloc { $if prealloc {

View File

@ -1126,6 +1126,9 @@ pub fn (s []string) join_lines() string {
// reverse will return a new reversed string. // reverse will return a new reversed string.
pub fn (s string) reverse() string { pub fn (s string) reverse() string {
if s.len == 0 {
return ''
}
mut res := string { mut res := string {
len: s.len len: s.len
str: malloc(s.len) str: malloc(s.len)

View File

@ -24,7 +24,11 @@ const (
* NB: if you need to decode many strings repeatedly, take a look at decode_in_buffer too. * NB: if you need to decode many strings repeatedly, take a look at decode_in_buffer too.
*/ */
pub fn decode(data string) string { 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) ) 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. * NB: if you need to encode many strings repeatedly, take a look at encode_in_buffer too.
*/ */
pub fn encode(data string) string { 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)) return tos(buffer, encode_in_buffer(data, buffer))
} }