From 3b7c0b4f2bebd9282c42b236ad910977e39e2cfc Mon Sep 17 00:00:00 2001 From: 94xhn <87560781+94xhn@users.noreply.github.com> Date: Wed, 15 Jul 2026 13:24:40 +0800 Subject: [PATCH] Fix memory leak when reusing DmtxEncode across multiple encode calls dmtxEncodeDataMatrix() unconditionally overwrote enc->message and enc->image on every call without freeing any previous values held by the same DmtxEncode struct. Reusing one DmtxEncode for multiple dmtxEncodeDataMatrix() calls (a supported and documented pattern) therefore leaked the prior message/image on each call. Free the existing enc->message and enc->image (mirroring the logic already used in dmtxEncodeDestroy()) immediately before allocating their replacements. This is a no-op on the first call, since both fields are NULL on a freshly created DmtxEncode. Fixes #40 --- dmtxencode.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/dmtxencode.c b/dmtxencode.c index c7f1794..adaa5cd 100644 --- a/dmtxencode.c +++ b/dmtxencode.c @@ -207,6 +207,10 @@ dmtxEncodeGetProp(DmtxEncode *enc, int prop) enc->region.mappingRows = dmtxGetSymbolAttribute(DmtxSymAttribMappingMatrixRows, sizeIdx); enc->region.mappingCols = dmtxGetSymbolAttribute(DmtxSymAttribMappingMatrixCols, sizeIdx); + /* Free any message left over from a previous call on this DmtxEncode + before allocating a new one, to avoid leaking it (see issue #40) */ + dmtxMessageDestroy(&(enc->message)); + /* Allocate memory for message and array */ enc->message = dmtxMessageCreate(sizeIdx, DmtxFormatMatrix); enc->message->padCount = 0; /* XXX this needs to be added back */ @@ -233,6 +237,14 @@ dmtxEncodeGetProp(DmtxEncode *enc, int prop) return DmtxFail; } + /* Free any image left over from a previous call on this DmtxEncode + before allocating a new one, to avoid leaking it (see issue #40) */ + if(enc->image != NULL && enc->image->pxl != NULL) { + free(enc->image->pxl); + enc->image->pxl = NULL; + } + dmtxImageDestroy(&(enc->image)); + enc->image = dmtxImageCreate(pxl, width, height, enc->pixelPacking); if(enc->image == NULL) { perror("image malloc error");