Add checks for memory allocation failures
Signed-off-by: Mahavir Jain <[email protected]>
diff --git a/examples/simplereader.c b/examples/simplereader.c
index 4752c08..1f00990 100644
--- a/examples/simplereader.c
+++ b/examples/simplereader.c
@@ -15,6 +15,8 @@
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;
diff --git a/src/cbortojson.c b/src/cbortojson.c
index a0f3262..4b11d31 100644
--- a/src/cbortojson.c
+++ b/src/cbortojson.c
@@ -179,6 +179,10 @@
/* 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 */
@@ -204,7 +208,12 @@
/* 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