Fam Zheng <f...@redhat.com> writes: > Zeroing a buffer that will be filled right after is not necessary, and > allocating a power of two + 1 is naughty. > > Suggested-by: Markus Armbruster <arm...@redhat.com> > Signed-off-by: Fam Zheng <f...@redhat.com> > --- > block/vmdk.c | 5 +++-- > 1 file changed, 3 insertions(+), 2 deletions(-) > > diff --git a/block/vmdk.c b/block/vmdk.c > index 28d22db..e863a09 100644 > --- a/block/vmdk.c > +++ b/block/vmdk.c > @@ -558,14 +558,15 @@ static char *vmdk_read_desc(BlockDriverState *file, > uint64_t desc_offset, > } > size = bdrv_getlength(file); if (size < 0) { error_setg_errno(errp, -size, "Could not access file"); return NULL; }
> size = MIN(size, 1 << 20); /* avoid unbounded allocation */ Consider the case where size <= 1 << 20, i.e. this line is a no-op. > - buf = g_malloc0(size + 1); > + buf = g_malloc(size); > > - ret = bdrv_pread(file, desc_offset, buf, size); > + ret = bdrv_pread(file, desc_offset, buf, size - 1); Then this reads everything except the last byte (thanks to Don for spotting it). > if (ret < 0) { > error_setg_errno(errp, -ret, "Could not read from file"); > g_free(buf); > return NULL; > } > + buf[ret] = 0; > > return buf; > } I figure Don suggested this instead: diff --git a/block/vmdk.c b/block/vmdk.c index 2cbfd3e..b7feb15 100644 --- a/block/vmdk.c +++ b/block/vmdk.c @@ -556,8 +556,8 @@ static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset, return NULL; } - size = MIN(size, 1 << 20); /* avoid unbounded allocation */ - buf = g_malloc0(size + 1); + size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */ + buf = g_malloc(size + 1); ret = bdrv_pread(file, desc_offset, buf, size); if (ret < 0) { @@ -565,6 +565,7 @@ static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset, g_free(buf); return NULL; } + buf[ret] = 0; return buf; }