Skip to content

Commit 4d786a0

Browse files
committed
REFTABLE_REALLOC_ARRAY: fix potential memory leak if realloc failed
REFTABLE_REALLOC_ARRAY doesn't free origin pointer when reftable_realloc failed. This leak can be fixed by add a free(x) before set x to NULL. Signed-off-by: Lidong Yan <[email protected]>
1 parent 6f84262 commit 4d786a0

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

reftable/basics.h

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -200,14 +200,26 @@ static inline int reftable_alloc_size(size_t nelem, size_t elsize, size_t *out)
200200
} \
201201
} while (0)
202202
#define REFTABLE_CALLOC_ARRAY(x, alloc) (x) = reftable_calloc((alloc), sizeof(*(x)))
203-
#define REFTABLE_REALLOC_ARRAY(x, alloc) do { \
204-
size_t alloc_size; \
205-
if (reftable_alloc_size(sizeof(*(x)), (alloc), &alloc_size) < 0) { \
206-
errno = ENOMEM; \
207-
(x) = NULL; \
208-
} else { \
209-
(x) = reftable_realloc((x), alloc_size); \
210-
} \
203+
#define REFTABLE_REALLOC_ARRAY(x, alloc) \
204+
do { \
205+
size_t alloc_size; \
206+
void *new_p; \
207+
if (reftable_alloc_size(sizeof(*(x)), (alloc), &alloc_size) < \
208+
0) { \
209+
goto cleanup; \
210+
} else { \
211+
new_p = reftable_realloc((x), alloc_size); \
212+
if (!new_p) { \
213+
goto cleanup; \
214+
} \
215+
(x) = new_p; \
216+
} \
217+
break; \
218+
cleanup: \
219+
if (x) \
220+
free(x); \
221+
errno = ENOMEM; \
222+
(x) = NULL; \
211223
} while (0)
212224

213225
static inline void *reftable_alloc_grow(void *p, size_t nelem, size_t elsize,

0 commit comments

Comments
 (0)