[Piglit] [PATCH 12/23] util: Add wrappers for malloc and calloc that catch errors

Kenneth Graunke kenneth at whitecape.org
Wed Oct 3 16:54:00 PDT 2012


On 09/28/2012 10:44 AM, Chad Versace wrote:
> Memory allocation should rarely fail, but when it does the test should
> immediately abort and explain why. This patch defines two utility wrapper
> functions, piglit_malloc() and piglit_calloc(), that do exactly that when
> allocation fails.
>
> Signed-off-by: Chad Versace <chad.versace at linux.intel.com>
> ---
>   tests/util/piglit-util.c | 26 ++++++++++++++++++++++++++
>   tests/util/piglit-util.h | 15 +++++++++++++++
>   2 files changed, 41 insertions(+)
>
> diff --git a/tests/util/piglit-util.c b/tests/util/piglit-util.c
> index 891ae22..e0e6c96 100644
> --- a/tests/util/piglit-util.c
> +++ b/tests/util/piglit-util.c
> @@ -406,3 +406,29 @@ write_null:
>   	va_end(va);
>   	return size_written;
>   }
> +
> +void*
> +piglit_malloc(size_t size)
> +{
> +	void *x = malloc(size);
> +
> +	if (x == NULL) {
> +		fprintf(stderr, "piglit: error: allocation failed\n");
> +		abort();
> +	}
> +
> +	return x;
> +}
> +
> +void*
> +piglit_calloc(size_t size)
> +{
> +	void *x = calloc(1, size);
> +
> +	if (x == NULL) {
> +		fprintf(stderr, "piglit: error: allocation failed\n");
> +		abort();
> +	}
> +
> +	return x;
> +}

I am really not a fan of malloc/calloc wrappers.  This change is 
well-intentioned, but I don't believe I've ever seen this work out in 
practice.

Mesa used to have malloc wrappers.  We removed them.  X has wrappers. 
People always wonder whether they have to use Xfree/Xmalloc or if they 
can just use plain malloc/free.  People wonder what the difference is. 
At the end of the day, projects don't end up using them consistently, at 
which point it's questionable whether it's worth having them.

If a program runs out of memory, it will likely die.  In my experience, 
it's not hard to tell when that happens.

Nacked-by: Kenneth Graunke <kenneth at whitecape.org>


More information about the Piglit mailing list