[PATCH v3] Re: avoid useless if-before-free tests
Janne Blomqvist
blomqvist.janne@gmail.com
Tue Mar 15 09:19:00 GMT 2011
On Tue, Mar 8, 2011 at 19:53, Jim Meyering <jim@meyering.net> wrote:
> Relative to v2, I've added libgo/ to the list of exempt directories and added
> this recently discussed gfc_free patch, at the request of Tobias Burnus.
> Also, I corrected an error in fortran's ChangeLog and removed all
> whitespace changes from all ChangeLog files.
The libgfortran changes are Ok for 4.7.
For the gfortran frontend (gcc/fortran/*) I'd prefer if you'd
- Replace all calls to "gfc_free (x)" with "free (x)".
- Remove the gfc_free() function and prototype.
- Remove the free() macro which currently prevents calling free() directly.
> From 0d18b70a8821ab2fc58b5ed592ed611e05a29c7f Mon Sep 17 00:00:00 2001
> From: Jim Meyering <meyering@redhat.com>
> Date: Mon, 3 Jan 2011 16:52:37 +0100
> Subject: [PATCH 1/2] discourage unnecessary use of if before free
>
> * README.Portability: Explain why "if (P) free (P)" is best avoided.
> ---
> gcc/README.Portability | 23 ++++++++++++++++-------
> 1 files changed, 16 insertions(+), 7 deletions(-)
>
> diff --git a/gcc/README.Portability b/gcc/README.Portability
> index 32a33e2..e099a3f 100644
> --- a/gcc/README.Portability
> +++ b/gcc/README.Portability
> @@ -51,14 +51,24 @@ foo (bar, )
> needs to be coded in some other way.
>
>
> -free and realloc
> -----------------
> +Avoid unnecessary test before free
> +----------------------------------
>
> -Some implementations crash upon attempts to free or realloc the null
> -pointer. Thus if mem might be null, you need to write
> +Since SunOS 4 stopped being a reasonable portability target,
> +(which happened around 2007) there has been no need to guard
> +against "free (NULL)". Thus, any guard like the following
> +constitutes a redundant test:
>
> - if (mem)
> - free (mem);
> + if (P)
> + free (P);
> +
> +It is better to avoid the test.[*]
> +Instead, simply free P, regardless of whether it is NULL.
> +
> +[*] However, if your profiling exposes a test like this in a
> +performance-critical loop, say where P is nearly always NULL, and
> +the cost of calling free on a NULL pointer would be prohibitively
> +high, please let us know.
Instead of "please let us know", maybe recommend using
__builtin_expect instead? E.g. something like
if (__builtin_expect (ptr != NULL, 0))
free (ptr);
--
Janne Blomqvist
More information about the Gcc-patches
mailing list