From cd9757512d6d49009ff3b7964ace194df84ce88b Mon Sep 17 00:00:00 2001 From: JKL Date: Fri, 24 Jun 2011 09:57:20 -0700 Subject: [PATCH] use size_t for strbuffer writes, and avoid integer overflow --- src/strbuffer.c | 11 +++++++++-- src/strbuffer.h | 6 +++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/strbuffer.c b/src/strbuffer.c index 1b20e2b..b9190c2 100644 --- a/src/strbuffer.c +++ b/src/strbuffer.c @@ -13,6 +13,7 @@ #define STRBUFFER_MIN_SIZE 16 #define STRBUFFER_FACTOR 2 +#define STRBUFFER_SIZE_MAX ((size_t)-1) int strbuffer_init(strbuffer_t *strbuff) { @@ -64,13 +65,19 @@ int strbuffer_append_byte(strbuffer_t *strbuff, char byte) return strbuffer_append_bytes(strbuff, &byte, 1); } -int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size) +int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, size_t size) { - if(strbuff->length + size >= strbuff->size) + if(size >= strbuff->size - strbuff->length) { size_t new_size; char *new_value; + /* avoid integer overflow */ + if (strbuff->size > STRBUFFER_SIZE_MAX / STRBUFFER_FACTOR + || size > STRBUFFER_SIZE_MAX - 1 + || strbuff->length > STRBUFFER_SIZE_MAX - 1 - size) + return -1; + new_size = max(strbuff->size * STRBUFFER_FACTOR, strbuff->length + size + 1); diff --git a/src/strbuffer.h b/src/strbuffer.h index b21ef8b..9764251 100644 --- a/src/strbuffer.h +++ b/src/strbuffer.h @@ -10,8 +10,8 @@ typedef struct { char *value; - int length; /* bytes used */ - int size; /* bytes allocated */ + size_t length; /* bytes used */ + size_t size; /* bytes allocated */ } strbuffer_t; int strbuffer_init(strbuffer_t *strbuff); @@ -24,7 +24,7 @@ char *strbuffer_steal_value(strbuffer_t *strbuff); int strbuffer_append(strbuffer_t *strbuff, const char *string); int strbuffer_append_byte(strbuffer_t *strbuff, char byte); -int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size); +int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, size_t size); char strbuffer_pop(strbuffer_t *strbuff);