Skip to content

Commit 7c349db

Browse files
mahavirjthiagomacieira
authored andcommitted
Add checks for memory allocation failures
Signed-off-by: Mahavir Jain <[email protected]>
1 parent 4a13b3e commit 7c349db

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

examples/simplereader.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ static uint8_t *readfile(const char *fname, size_t *size)
1515
if (fstat(fileno(f), &st) == -1)
1616
return NULL;
1717
uint8_t *buf = malloc(st.st_size);
18+
if (buf == NULL)
19+
return NULL;
1820
*size = fread(buf, st.st_size, 1, f) == 1 ? st.st_size : 0;
1921
fclose(f);
2022
return buf;

src/cbortojson.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ static CborError dump_bytestring_base16(char **result, CborValue *it)
179179

180180
/* a Base16 (hex) output is twice as big as our buffer */
181181
buffer = (uint8_t *)malloc(n * 2 + 1);
182+
if (buffer == NULL)
183+
/* out of memory */
184+
return CborErrorOutOfMemory;
185+
182186
*result = (char *)buffer;
183187

184188
/* let cbor_value_copy_byte_string know we have an extra byte for the terminating NUL */
@@ -204,7 +208,12 @@ static CborError generic_dump_base64(char **result, CborValue *it, const char al
204208

205209
/* a Base64 output (untruncated) has 4 bytes for every 3 in the input */
206210
size_t len = (n + 5) / 3 * 4;
207-
out = buffer = (uint8_t *)malloc(len + 1);
211+
buffer = (uint8_t *)malloc(len + 1);
212+
if (buffer == NULL)
213+
/* out of memory */
214+
return CborErrorOutOfMemory;
215+
216+
out = buffer;
208217
*result = (char *)buffer;
209218

210219
/* we read our byte string at the tail end of the buffer

0 commit comments

Comments
 (0)