Fix panic when size 0 passed to malloc

Этот коммит содержится в:
Anuraag Agrawal 2022-11-21 13:25:24 +09:00 коммит произвёл Ron Evans
родитель c759e6fc2d
коммит b731919f97
2 изменённых файлов: 37 добавлений и 0 удалений

Просмотреть файл

@ -13,6 +13,9 @@ var allocs = make(map[uintptr][]byte)
//export malloc
func libc_malloc(size uintptr) unsafe.Pointer {
if size == 0 {
return nil
}
buf := make([]byte, size)
ptr := unsafe.Pointer(&buf[0])
allocs[uintptr(ptr)] = buf
@ -39,6 +42,11 @@ func libc_calloc(nmemb, size uintptr) unsafe.Pointer {
//export realloc
func libc_realloc(oldPtr unsafe.Pointer, size uintptr) unsafe.Pointer {
if size == 0 {
libc_free(oldPtr)
return nil
}
// It's hard to optimize this to expand the current buffer with our GC, but
// it is theoretically possible. For now, just always allocate fresh.
buf := make([]byte, size)

Просмотреть файл

@ -125,3 +125,32 @@ func TestMallocFree(t *testing.T) {
})
}
}
func TestMallocEmpty(t *testing.T) {
ptr := libc_malloc(0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}
func TestCallocEmpty(t *testing.T) {
ptr := libc_calloc(0, 1)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
ptr = libc_calloc(1, 0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}
func TestReallocEmpty(t *testing.T) {
ptr := libc_malloc(1)
if ptr == nil {
t.Error("expected pointer but was nil")
}
ptr = libc_realloc(ptr, 0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}