Skip to content

Commit

Permalink
Add checks for memory allocation failures
Browse files Browse the repository at this point in the history
Signed-off-by: Mahavir Jain <[email protected]>
  • Loading branch information
mahavirj authored and thiagomacieira committed Feb 25, 2021
1 parent 4a13b3e commit 7c349db
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions examples/simplereader.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ static uint8_t *readfile(const char *fname, size_t *size)
if (fstat(fileno(f), &st) == -1)
return NULL;
uint8_t *buf = malloc(st.st_size);
if (buf == NULL)
return NULL;
*size = fread(buf, st.st_size, 1, f) == 1 ? st.st_size : 0;
fclose(f);
return buf;
Expand Down
11 changes: 10 additions & 1 deletion src/cbortojson.c
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@ static CborError dump_bytestring_base16(char **result, CborValue *it)

/* a Base16 (hex) output is twice as big as our buffer */
buffer = (uint8_t *)malloc(n * 2 + 1);
if (buffer == NULL)
/* out of memory */
return CborErrorOutOfMemory;

*result = (char *)buffer;

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

/* a Base64 output (untruncated) has 4 bytes for every 3 in the input */
size_t len = (n + 5) / 3 * 4;
out = buffer = (uint8_t *)malloc(len + 1);
buffer = (uint8_t *)malloc(len + 1);
if (buffer == NULL)
/* out of memory */
return CborErrorOutOfMemory;

out = buffer;
*result = (char *)buffer;

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

0 comments on commit 7c349db

Please sign in to comment.