From 3b49ac2c5d68be26ebe3a486cec699c1a7a89263 Mon Sep 17 00:00:00 2001 From: jmjatlanta Date: Fri, 23 Dec 2016 20:10:52 -0500 Subject: [PATCH] Better allocation of memory for strings with zero bytes --- protobuf.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/protobuf.c b/protobuf.c index 5e1d6da..805fd05 100644 --- a/protobuf.c +++ b/protobuf.c @@ -116,21 +116,21 @@ int protobuf_decode_string(const unsigned char* buffer, size_t buffer_length, ch // grab the field size int length = varint_decode(&buffer[pos], buffer_length - pos, bytes_read); pos += *bytes_read; + *bytes_read += length; - // allocate memory - *results = malloc(sizeof(char) * length + 1); - if ((*results) == NULL) - return 0; + // allocate memory (if neccesary) + if (length > 0) { + *results = malloc(sizeof(char) * length + 1); + if ((*results) == NULL) + return 0; - memset(*results, 0, length+1); - - // copy the string - memcpy((*results), &buffer[pos], length); - // don't forget the null - (*results)[length] = 0; - pos += length; - *bytes_read = pos; + memset(*results, 0, length+1); + // copy the string + memcpy((*results), &buffer[pos], length); + // don't forget the null + (*results)[length] = 0; + } return 1; }