util: alloc: Add automatic cleanup/disposal of strings

VIR_AUTODISPOSE_STR is similar to VIR_AUTOFREE(char *) but uses
virDispose for clearing of the stored string.

This patch also refactors VIR_DISPOSE to use the new helper which is
used for the new macro.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
This commit is contained in:
Peter Krempa 2019-04-01 15:04:53 +02:00
parent c358adc571
commit a9b3afabcd
3 changed files with 29 additions and 2 deletions

View File

@ -1428,6 +1428,7 @@ virAllocTestOOM;
virAllocVar; virAllocVar;
virDeleteElementsN; virDeleteElementsN;
virDispose; virDispose;
virDisposeString;
virExpandN; virExpandN;
virFree; virFree;
virInsertElementsN; virInsertElementsN;

View File

@ -618,3 +618,19 @@ void virDispose(void *ptrptr,
*countptr = 0; *countptr = 0;
errno = save_errno; errno = save_errno;
} }
/**
* virDisposeString:
* @ptrptr: pointer to pointer for a string which should be sanitized and cleared
*
* See virDispose.
*/
void
virDisposeString(char **strptr)
{
if (!*strptr)
return;
virDispose(strptr, strlen(*strptr), sizeof(char), NULL);
}

View File

@ -79,6 +79,8 @@ void virFree(void *ptrptr) ATTRIBUTE_NONNULL(1);
void virDispose(void *ptrptr, size_t count, size_t element_size, size_t *countptr) void virDispose(void *ptrptr, size_t count, size_t element_size, size_t *countptr)
ATTRIBUTE_NONNULL(1); ATTRIBUTE_NONNULL(1);
void virDisposeString(char **strptr)
ATTRIBUTE_NONNULL(1);
/** /**
* VIR_ALLOC: * VIR_ALLOC:
@ -575,9 +577,17 @@ void virDispose(void *ptrptr, size_t count, size_t element_size, size_t *countpt
* *
* This macro is not safe to be used on arguments with side effects. * This macro is not safe to be used on arguments with side effects.
*/ */
# define VIR_DISPOSE_STRING(ptr) virDispose(1 ? (void *) &(ptr) : (ptr), \ # define VIR_DISPOSE_STRING(ptr) virDisposeString(&(ptr))
(ptr) ? strlen((ptr)) : 0, 1, NULL)
/**
* VIR_AUTODISPOSE_STR:
*
* Macro to automatically free and clear the memory allocated to
* the string variable declared with it by calling virDisposeString
* when the variable goes out of scope.
*/
# define VIR_AUTODISPOSE_STR \
__attribute__((cleanup(virDisposeString))) char *
/** /**
* VIR_DISPOSE: * VIR_DISPOSE: