buf: add a test against SIZE_MAX when doubling

Wed, 16 Dec 2020 16:12:31 +0100

author
David Demelier <markand@malikania.fr>
date
Wed, 16 Dec 2020 16:12:31 +0100
changeset 17
2694997c4c90
parent 16
54638f36f774
child 18
7f5b3f035bef

buf: add a test against SIZE_MAX when doubling

While here, explain more what the code does at some points.

buf.c file | annotate | diff | comparison | revisions
--- a/buf.c	Wed Dec 16 16:11:16 2020 +0100
+++ b/buf.c	Wed Dec 16 16:12:31 2020 +0100
@@ -39,6 +39,7 @@
 	while (desired > newcap - b->length) {
 		const size_t r = newcap * 2;
 
+		/* Overflow occured. */
 		if (r / newcap != 2) {
 #if defined(ENOMEM)
 			errno = ENOMEM;
@@ -52,6 +53,14 @@
 	/* At this step we must have enough room. */
 	assert(newcap - b->length >= desired);
 
+	/* Pretty much impossible to reach but always assume it's possible. */
+	if (newcap == SIZE_MAX) {
+#if defined(ENOMEM)
+		errno = ENOMEM;
+#endif
+		return false;
+	}
+
 	if (!(newptr = BUF_REALLOC(b->data, newcap + 1)))
 		return false;
 
@@ -94,6 +103,10 @@
 	return true;
 }
 
+/*
+ * Entry point for reallocating data. Will try to allocate twice until we have
+ * enough room and then only the minimal amount.
+ */
 bool
 _buf_grow(struct buf *b, size_t desired)
 {

mercurial