Better allocation of memory for strings with zero bytes

This commit is contained in:
jmjatlanta 2016-12-23 20:10:52 -05:00
parent 8d966178f4
commit 3b49ac2c5d

View file

@ -116,21 +116,21 @@ int protobuf_decode_string(const unsigned char* buffer, size_t buffer_length, ch
// grab the field size // grab the field size
int length = varint_decode(&buffer[pos], buffer_length - pos, bytes_read); int length = varint_decode(&buffer[pos], buffer_length - pos, bytes_read);
pos += *bytes_read; pos += *bytes_read;
*bytes_read += length;
// allocate memory // allocate memory (if neccesary)
*results = malloc(sizeof(char) * length + 1); if (length > 0) {
if ((*results) == NULL) *results = malloc(sizeof(char) * length + 1);
return 0; if ((*results) == NULL)
return 0;
memset(*results, 0, length+1); 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;
// copy the string
memcpy((*results), &buffer[pos], length);
// don't forget the null
(*results)[length] = 0;
}
return 1; return 1;
} }