Mercurial > dropbear
diff buffer.c @ 1057:16584026a1f0 nocircbuffer
allocate buffer and data in a single allocation
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Sun, 01 Mar 2015 21:16:09 +0800 |
parents | a5b785c12340 |
children | 2fa71c3b2827 aaf576b27a10 |
line wrap: on
line diff
--- a/buffer.c Sun Mar 01 14:46:04 2015 +0800 +++ b/buffer.c Sun Mar 01 21:16:09 2015 +0800 @@ -46,17 +46,15 @@ dropbear_exit("buf->size too big"); } - buf = (buffer*)m_malloc(sizeof(buffer)); + buf = (buffer*)m_malloc(sizeof(buffer)+size); if (size > 0) { - buf->data = (unsigned char*)m_malloc(size); + buf->data = (unsigned char*)buf + sizeof(buffer); } else { buf->data = NULL; } buf->size = size; - buf->pos = 0; - buf->len = 0; return buf; @@ -65,7 +63,6 @@ /* free the buffer's data and the buffer itself */ void buf_free(buffer* buf) { - m_free(buf->data) m_free(buf); } @@ -78,17 +75,18 @@ /* resize a buffer, pos and len will be repositioned if required when * downsizing */ -void buf_resize(buffer *buf, unsigned int newsize) { +buffer* buf_resize(buffer *buf, unsigned int newsize) { if (newsize > BUF_MAX_SIZE) { dropbear_exit("buf->size too big"); } - buf->data = m_realloc(buf->data, newsize); + buf = m_realloc(buf, sizeof(buffer)+newsize); + buf->data = (unsigned char*)buf + sizeof(buffer); buf->size = newsize; buf->len = MIN(newsize, buf->len); buf->pos = MIN(newsize, buf->pos); - + return buf; } /* Create a copy of buf, allocating required memory etc. */ @@ -227,15 +225,15 @@ /* Return a string as a newly allocated buffer */ buffer * buf_getstringbuf(buffer *buf) { - buffer *ret; - unsigned char* str; - unsigned int len; - str = buf_getstring(buf, &len); - ret = m_malloc(sizeof(*ret)); - ret->data = str; - ret->len = len; - ret->size = len; - ret->pos = 0; + buffer *ret = NULL; + unsigned int len = buf_getint(buf); + if (len > MAX_STRING_LEN) { + dropbear_exit("String too long"); + } + ret = buf_new(len); + memcpy(buf_getwriteptr(ret, len), buf_getptr(buf, len), len); + buf_incrpos(buf, len); + buf_incrlen(ret, len); return ret; }