From 1f40bca91cdbf7f5c1366f5d34e89f9e2920f91d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Deltheil?= Date: Tue, 8 Jan 2013 23:45:55 +0100 Subject: [PATCH 1/2] Make it safe to always use `data` as a character string --- buffer.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/buffer.c b/buffer.c index 8e9380d..d489fbd 100644 --- a/buffer.c +++ b/buffer.c @@ -39,7 +39,7 @@ buffer_new_with_size(size_t n) { buffer_t *self = malloc(sizeof(buffer_t)); if (!self) return NULL; self->len = n; - self->data = self->alloc = calloc(n, 1); + self->data = self->alloc = calloc(n + 1, 1); return self; } @@ -88,7 +88,7 @@ ssize_t buffer_compact(buffer_t *self) { size_t len = buffer_length(self); size_t rem = self->len - len; - char *buf = calloc(len, 1); + char *buf = calloc(len + 1, 1); if (!buf) return -1; memcpy(buf, self->data, len); free(self->alloc); @@ -133,7 +133,7 @@ int buffer_resize(buffer_t *self, size_t n) { n = nearest_multiple_of(1024, n); self->len = n; - self->alloc = self->data = realloc(self->alloc, n); + self->alloc = self->data = realloc(self->alloc, n + 1); return self->alloc ? 0 : -1; } @@ -205,7 +205,7 @@ buffer_slice(buffer_t *buf, size_t from, ssize_t to) { if (to > len) to = len; size_t n = to - from; - buffer_t *self = buffer_new_with_size(n + 1); + buffer_t *self = buffer_new_with_size(n); memcpy(self->data, buf->data + from, n); return self; } From a46a370c3569757924fd521efb7467076a687514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Deltheil?= Date: Wed, 9 Jan 2013 16:08:54 +0100 Subject: [PATCH 2/2] Add missing null terminator after realloc (buffer resize) --- buffer.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/buffer.c b/buffer.c index d489fbd..e35b36a 100644 --- a/buffer.c +++ b/buffer.c @@ -134,7 +134,9 @@ buffer_resize(buffer_t *self, size_t n) { n = nearest_multiple_of(1024, n); self->len = n; self->alloc = self->data = realloc(self->alloc, n + 1); - return self->alloc ? 0 : -1; + if (!self->alloc) return -1; + self->alloc[n] = '\0'; + return 0; } /*