[PATCH 1/2] Introduce xmalloc, memory allocator with die_out_of_memory()

Dmitry V. Levin ldv at altlinux.org
Thu Mar 26 17:06:06 UTC 2015


On Thu, Mar 26, 2015 at 02:32:33AM +0900, Masatake YAMATO wrote:
> In strace following code sentences are frequently used:
> 
>    var = malloc(fdsize);
>     if (!var)
>        die_out_of_memory();
> 
> This patch introduces xmalloc and friends which simplify
> above sentences like:
> 
>    var = xmalloc(fdsize);
> 
> Here friends are xcalloc and xrealloc.
> 
> * defs.h: (xmalloc, xcalloc, xrealloc): New declarations.

Adding these declarations without proper malloc and alloc_size attributes
would be a regression.

> * strace.c (xmalloc, xcalloc, xrealloc): New functions.

strace.c is already loaded with a lot of more or less unrelated functions.
Let's not follow this practice and put these new functions to a separate
file.

[...]
> --- a/defs.h
> +++ b/defs.h
> @@ -398,6 +398,13 @@ void error_msg_and_die(const char *fmt, ...) __attribute__ ((noreturn, format(pr
>  void perror_msg_and_die(const char *fmt, ...) __attribute__ ((noreturn, format(printf, 1, 2)));
>  void die_out_of_memory(void) __attribute__ ((noreturn));
>  
> +/*
> + * Memory allocator + die_out_of_memory
> + */
> +void *xmalloc(size_t size);
> +void *xcalloc(size_t nmmeb, size_t size);
> +void *xrealloc(void *ptr, size_t size);
> +

It has to be something like this:

#ifndef attribute_malloc
# if gnuc_prereq(3, 0)
#  define attribute_malloc __attribute__((__malloc__))
# else
#  define attribute_malloc
# endif
#endif

#ifndef alloc_size
# if gnuc_prereq(4, 3)
#  define attribute_alloc_size(args) __attribute__((__alloc_size__ args))
# else
#  define attribute_alloc_size(args)
# endif
#endif

void *xmalloc(size_t size) attribute_malloc attribute_alloc_size((1));
void *xcalloc(size_t nmmeb, size_t size) attribute_malloc attribute_alloc_size((1, 2));
void *xrealloc(void *ptr, size_t size) attribute_alloc_size((2));
void *xreallocarray(void *ptr, size_t nmmeb, size_t size) attribute_alloc_size((2, 3));


-- 
ldv
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.strace.io/pipermail/strace-devel/attachments/20150326/615048a6/attachment.bin>


More information about the Strace-devel mailing list