strbuf: release memory on read error in strbuf_read_once()

If other strbuf add functions cause the first allocation and
subsequently encounter an error then they release the memory, restoring
the pristine state of the strbuf.  That simplifies error handling for

Do the same in strbuf_read_once(), and do it also in case no bytes were
read -- which may or may not be an error as well, depending on the

Signed-off-by: Rene Scharfe <>
Signed-off-by: Junio C Hamano <>
This commit is contained in:
René Scharfe 2017-12-07 21:51:26 +01:00 committed by Junio C Hamano
parent 9752ad0bb7
commit c3ff8f6c14
1 changed files with 3 additions and 0 deletions

View File

@ -393,12 +393,15 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
size_t oldalloc = sb->alloc;
ssize_t cnt;
strbuf_grow(sb, hint ? hint : 8192);
cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
if (cnt > 0)
strbuf_setlen(sb, sb->len + cnt);
else if (oldalloc == 0)
return cnt;