Skip to content

Commit 6f813dc

Browse files
fix: check return values of malloc in xbm2fb and realloc in cfg_desc_append (#132)
- Switch malloc+memset to calloc in xbm2fb(); return early on NULL - Guard cfg_desc_append() against realloc failure using temp pointer - Add PRINT diagnostic on allocation failure - Include debug.h in setup.c and xbm.c
1 parent 1baeda2 commit 6f813dc

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

src/usb/setup.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#include <stdlib.h>
2-
2+
#include "../debug.h"
33
#include "CH58x_common.h"
44

55
#include "utils.h"
@@ -30,7 +30,12 @@ void cfg_desc_append(void *desc)
3030
cfg_len = ((USB_CFG_DESCR *)cfg_desc)->wTotalLength;
3131
uint8_t newlen = cfg_len + len;
3232

33-
cfg_desc = realloc(cfg_desc, newlen); // TODO: add a safe check here
33+
uint8_t *tmp = realloc(cfg_desc, newlen);
34+
if (!tmp) {
35+
printf("cfg_desc_append: out of memory\n");
36+
return;
37+
}
38+
cfg_desc = tmp;
3439

3540
memcpy(cfg_desc + cfg_len, desc, len);
3641

src/xbm.c

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "xbm.h"
22
#include <stdlib.h>
33
#include <memory.h>
4+
#include "debug.h"
45

56
/**
67
* Draw bitmap file to fb at (col, row)
@@ -9,9 +10,11 @@
910
void xbm2fb(xbm_t *xbm, uint16_t *fb, int col, int row)
1011
{
1112
int W = ALIGN_8BIT(xbm->w);
12-
uint16_t *tmpfb = malloc(W * sizeof(uint16_t));
13-
memset(tmpfb, 0, W * sizeof(uint16_t));
14-
13+
uint16_t *tmpfb = calloc(W, sizeof(*tmpfb));
14+
if (!tmpfb) {
15+
printf("xbm2fb: out of memory\n");
16+
return;
17+
}
1518
if ((xbm->h + row) >= 0 && col >= 0) {
1619

1720
for (int h = 0; h < xbm->h; h++) {

0 commit comments

Comments
 (0)