Skip to content

Commit b731919

Browse files
anuraagadeadprogram
authored andcommitted
Fix panic when size 0 passed to malloc
1 parent c759e6f commit b731919

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/runtime/arch_tinygowasm_malloc.go

+8
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ var allocs = make(map[uintptr][]byte)
1313

1414
//export malloc
1515
func libc_malloc(size uintptr) unsafe.Pointer {
16+
if size == 0 {
17+
return nil
18+
}
1619
buf := make([]byte, size)
1720
ptr := unsafe.Pointer(&buf[0])
1821
allocs[uintptr(ptr)] = buf
@@ -39,6 +42,11 @@ func libc_calloc(nmemb, size uintptr) unsafe.Pointer {
3942

4043
//export realloc
4144
func libc_realloc(oldPtr unsafe.Pointer, size uintptr) unsafe.Pointer {
45+
if size == 0 {
46+
libc_free(oldPtr)
47+
return nil
48+
}
49+
4250
// It's hard to optimize this to expand the current buffer with our GC, but
4351
// it is theoretically possible. For now, just always allocate fresh.
4452
buf := make([]byte, size)

tests/runtime_wasi/malloc_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -125,3 +125,32 @@ func TestMallocFree(t *testing.T) {
125125
})
126126
}
127127
}
128+
129+
func TestMallocEmpty(t *testing.T) {
130+
ptr := libc_malloc(0)
131+
if ptr != nil {
132+
t.Errorf("expected nil pointer, got %p", ptr)
133+
}
134+
}
135+
136+
func TestCallocEmpty(t *testing.T) {
137+
ptr := libc_calloc(0, 1)
138+
if ptr != nil {
139+
t.Errorf("expected nil pointer, got %p", ptr)
140+
}
141+
ptr = libc_calloc(1, 0)
142+
if ptr != nil {
143+
t.Errorf("expected nil pointer, got %p", ptr)
144+
}
145+
}
146+
147+
func TestReallocEmpty(t *testing.T) {
148+
ptr := libc_malloc(1)
149+
if ptr == nil {
150+
t.Error("expected pointer but was nil")
151+
}
152+
ptr = libc_realloc(ptr, 0)
153+
if ptr != nil {
154+
t.Errorf("expected nil pointer, got %p", ptr)
155+
}
156+
}

0 commit comments

Comments
 (0)