Skip to content

Commit c1a8d48

Browse files
authored
Merge pull request #766 from RubenKelevra/bugfix/memory_leak_to_bmp_jpg2bmp
jpg2bmp: fix memory leak on error
2 parents ed74d59 + 0c72514 commit c1a8d48

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

conversions/to_bmp.c

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414
#include <stddef.h>
1515
#include <string.h>
16+
#include <stdlib.h>
1617
#include "img_converters.h"
1718
#include "soc/efuse_reg.h"
1819
#include "esp_heap_caps.h"
@@ -114,28 +115,31 @@ bool jpg2bmp(const uint8_t *src, size_t src_len, uint8_t ** out, size_t * out_le
114115
.advanced.working_buffer = work,
115116
.advanced.working_buffer_size = sizeof(work),
116117
};
117-
118+
119+
bool ret = false;
120+
uint8_t *output = NULL;
118121
esp_jpeg_image_output_t output_img = {};
119122
if (esp_jpeg_get_image_info(&jpeg_cfg, &output_img) != ESP_OK) {
120123
ESP_LOGE(TAG, "Failed to get image info");
121-
return false;
124+
goto fail;
122125
}
123-
126+
124127
// @todo here we allocate memory and we assume that the user will free it
125128
// this is not the best way to do it, but we need to keep the API
126129
// compatible with the previous version
127130
const size_t output_size = output_img.output_len + BMP_HEADER_LEN;
128-
uint8_t *output = _malloc(output_size);
131+
output = _malloc(output_size);
129132
if (!output) {
130133
ESP_LOGE(TAG, "Failed to allocate output buffer");
131-
return false;
134+
goto fail;
132135
}
133136

134137
// Start writing decoded data after the BMP header
135138
jpeg_cfg.outbuf = output + BMP_HEADER_LEN;
136139
jpeg_cfg.outbuf_size = output_img.output_len;
137140
if(esp_jpeg_decode(&jpeg_cfg, &output_img) != ESP_OK){
138-
return false;
141+
ESP_LOGE(TAG, "JPEG decode failed");
142+
goto fail;
139143
}
140144

141145
output[0] = 'B';
@@ -158,8 +162,13 @@ bool jpg2bmp(const uint8_t *src, size_t src_len, uint8_t ** out, size_t * out_le
158162

159163
*out = output;
160164
*out_len = output_size;
165+
ret = true;
161166

162-
return true;
167+
fail:
168+
if (!ret && output) {
169+
free(output);
170+
}
171+
return ret;
163172
}
164173

165174
bool fmt2rgb888(const uint8_t *src_buf, size_t src_len, pixformat_t format, uint8_t * rgb_buf)

0 commit comments

Comments
 (0)