[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Qemu-devel] [PATCH v2 0/3] require newer glib2 to enable autofree'i
From: |
Daniel P . Berrangé |
Subject: |
Re: [Qemu-devel] [PATCH v2 0/3] require newer glib2 to enable autofree'ing of stack variables exiting scope |
Date: |
Wed, 31 Jul 2019 15:10:55 +0100 |
User-agent: |
Mutt/1.12.0 (2019-05-25) |
On Wed, Jul 31, 2019 at 03:04:29PM +0100, Alex Bennée wrote:
>
> Daniel P. Berrangé <address@hidden> writes:
>
> > Both GCC and CLang support a C extension attribute((cleanup)) which
> > allows you to define a function that is invoked when a stack variable
> > exits scope. This typically used to free the memory allocated to it,
> > though you're not restricted to this. For example it could be used to
> > unlock a mutex.
> <snip>
> >
> > GOOD:
> > g_autofree char *wibble = g_strdup("wibble")
> > ...
> > return g_steal_pointer(wibble);
> >
> > g_steal_pointer is an inline function which simply copies
> > the pointer to a new variable, and sets the original variable
> > to NULL, thus avoiding cleanup.
>
> Surely this is a particular use case where you wouldn't use g_autofree
> to declare the variable as you intending to return it to the outer scope?
I think it depends on the situation. Obviously real code will have
something in the "..." part I snipped.
You have 20 code paths that can result in returning with an error, where
you want to have all variables freed, and only 1 code path for success
Then it makes sense to use g_autofree + g_steal_pointer to eliminate
many goto jumps.
If you have only 1 error path and 1 success path, then a traditional
g_free() call is may well be sufficient.
IOW, as with many coding "rules", there's scope to use personal
judgement as to when it is right to ignore it vs folow it.
Regards,
Daniel
--
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org -o- https://fstop138.berrange.com :|
|: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
- [Qemu-devel] [PATCH v2 0/3] require newer glib2 to enable autofree'ing of stack variables exiting scope, Daniel P . Berrangé, 2019/07/25
- [Qemu-devel] [PATCH v2 1/3] glib: bump min required glib library version to 2.48, Daniel P . Berrangé, 2019/07/25
- [Qemu-devel] [PATCH v2 2/3] crypto: define cleanup functions for use with g_autoptr, Daniel P . Berrangé, 2019/07/25
- [Qemu-devel] [PATCH v2 3/3] crypto: use auto cleanup for many stack variables, Daniel P . Berrangé, 2019/07/25
- Re: [Qemu-devel] [PATCH v2 0/3] require newer glib2 to enable autofree'ing of stack variables exiting scope, Marc-André Lureau, 2019/07/31
- Re: [Qemu-devel] [PATCH v2 0/3] require newer glib2 to enable autofree'ing of stack variables exiting scope, Alex Bennée, 2019/07/31