util: buffer: Introduce VIR_AUTOCLEAN function for virBuffer

virBuffer is almost always stack-allocated, but requires freeing of the
internals on error. Introduce a VIR_AUTOCLEAN function to deal with
this.

Along with the addition add a test which would leak the buffer contents
if it weren't autocleaned.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
This commit is contained in:
Peter Krempa 2019-02-21 16:37:50 +01:00
parent c73f752e46
commit 55ee6ac8de
2 changed files with 15 additions and 0 deletions

View File

@ -59,6 +59,9 @@ int virBufferCheckErrorInternal(const virBuffer *buf,
const char *funcname,
size_t linenr)
ATTRIBUTE_NONNULL(1);
VIR_DEFINE_AUTOCLEAN_FUNC(virBuffer, virBufferFreeAndReset);
/**
* virBufferCheckError
*

View File

@ -429,6 +429,17 @@ testBufSetIndent(const void *opaque ATTRIBUTE_UNUSED)
}
/* Result of this shows up only in valgrind or similar */
static int
testBufferAutoclean(const void *opaque ATTRIBUTE_UNUSED)
{
VIR_AUTOCLEAN(virBuffer) buf = VIR_BUFFER_INITIALIZER;
virBufferAddLit(&buf, "test test test\n");
return 0;
}
static int
mymain(void)
{
@ -448,6 +459,7 @@ mymain(void)
DO_TEST("Trim", testBufTrim, 0);
DO_TEST("AddBuffer", testBufAddBuffer, 0);
DO_TEST("set indent", testBufSetIndent, 0);
DO_TEST("autoclean", testBufferAutoclean, 0);
#define DO_TEST_ADD_STR(DATA, EXPECT) \
do { \