From 1fabc3b466018e26226abffb47c3ae7026be5988 Mon Sep 17 00:00:00 2001 From: Rohan Singh Date: Tue, 2 Aug 2022 18:19:33 -0400 Subject: [PATCH] Fix memory leak in animation encoding (#1) We were never freeing the buffer that holds the assembled WebP animation. Instead, copy the buffer into Go and free it right after assembly. --- webp/anim_encode.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/webp/anim_encode.go b/webp/anim_encode.go index cc5e2c9..f3960c7 100644 --- a/webp/anim_encode.go +++ b/webp/anim_encode.go @@ -107,15 +107,26 @@ func (ae *AnimationEncoder) Assemble() ([]byte, error) { data := &C.WebPData{} C.WebPDataInit(data) + defer C.WebPDataClear(data) if C.WebPAnimEncoderAssemble(ae.c, data) == 0 { return nil, errors.New("Error assembling animation") } - return C.GoBytes( - unsafe.Pointer(data.bytes), - C.int(int(data.size)), - ), nil + size := int(data.size) + out := make([]byte, size) + n := copy( + out, C.GoBytes( + unsafe.Pointer(data.bytes), + C.int(size), + ), + ) + + if n != size { + return nil, errors.New("Error copying animation from C to Go") + } + + return out, nil } // Close deletes the encoder and frees resources.