Fix panic when size 0 passed to malloc
Этот коммит содержится в:
родитель
c759e6fc2d
коммит
b731919f97
2 изменённых файлов: 37 добавлений и 0 удалений
|
@ -13,6 +13,9 @@ var allocs = make(map[uintptr][]byte)
|
||||||
|
|
||||||
//export malloc
|
//export malloc
|
||||||
func libc_malloc(size uintptr) unsafe.Pointer {
|
func libc_malloc(size uintptr) unsafe.Pointer {
|
||||||
|
if size == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
buf := make([]byte, size)
|
buf := make([]byte, size)
|
||||||
ptr := unsafe.Pointer(&buf[0])
|
ptr := unsafe.Pointer(&buf[0])
|
||||||
allocs[uintptr(ptr)] = buf
|
allocs[uintptr(ptr)] = buf
|
||||||
|
@ -39,6 +42,11 @@ func libc_calloc(nmemb, size uintptr) unsafe.Pointer {
|
||||||
|
|
||||||
//export realloc
|
//export realloc
|
||||||
func libc_realloc(oldPtr unsafe.Pointer, size uintptr) unsafe.Pointer {
|
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's hard to optimize this to expand the current buffer with our GC, but
|
||||||
// it is theoretically possible. For now, just always allocate fresh.
|
// it is theoretically possible. For now, just always allocate fresh.
|
||||||
buf := make([]byte, size)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Загрузка…
Создание таблицы
Сослаться в новой задаче