Browse Source

sprintbuf(): handle printbuf_memappend errors

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.
tags/json-c-0.16-20220414
Tobias Stoeckmann 3 years ago
parent
commit
d07da04c14
1 changed files with 3 additions and 4 deletions
  1. +3
    -4
      printbuf.c

+ 3
- 4
printbuf.c View 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)


Loading…
Cancel
Save