]> granicus.if.org Git - json-c/commitdiff
sprintbuf(): handle printbuf_memappend errors
authorTobias Stoeckmann <tobias@stoeckmann.org>
Thu, 3 Mar 2022 20:24:27 +0000 (21:24 +0100)
committerTobias Stoeckmann <tobias@stoeckmann.org>
Thu, 3 Mar 2022 20:24:27 +0000 (21:24 +0100)
If errors occur in printbuf_memappend, then these errors should be
propagated through sprintbuf to indicate the error to the user.

Proof of Concept:
```
 #include <err.h>
 #include <limits.h>
 #include <stdio.h>

 #include "json.h"

 int
 main(void) {
  struct printbuf *pb;
  if ((pb = printbuf_new()) == NULL)
   err(1, "printbuf_new");
  if (printbuf_memset(pb, INT_MAX - 9, 'a', 1) < 0)
   errx(1, "printbuf_memset");
  printf("length: %d\n", printbuf_length(pb));
  printf("sprintbuf: %d\n", sprintbuf(pb, "string too long"));
  printf("length: %d\n", printbuf_length(pb));
  printbuf_free(pb);
  return 0;
 }
```

You can see that sprintbuf does not return an error but length is still
the same, i.e. the string "string too long" has not been appended.

I would like to add this as a unit test but it really depends on the
operating system if printbuf_memset() would fail if not enough memory is
available or not.

printbuf.c

index 00822fac4f19ebe6f9a5aaafea51ebf38070086b..48e8101e12ae7ac523f29930eb9f11ef1c23b736 100644 (file)
@@ -152,15 +152,14 @@ int sprintbuf(struct printbuf *p, const char *msg, ...)
                        return -1;
                }
                va_end(ap);
-               printbuf_memappend(p, t, size);
+               size = printbuf_memappend(p, t, size);
                free(t);
-               return size;
        }
        else
        {
-               printbuf_memappend(p, buf, size);
-               return size;
+               size = printbuf_memappend(p, buf, size);
        }
+       return size;
 }
 
 void printbuf_reset(struct printbuf *p)