[PATCH] malloc: Add asserts for malloc assumptions

Adhemerval Zanella Netto adhemerval.zanella@linaro.org
Mon Mar 2 13:33:10 GMT 2026



On 02/03/26 10:17, Wilco Dijkstra wrote:
> 
> Currently malloc has various assumptions, some documented, some implicit.
> Add a few static asserts to check the most fundamental assumptions.
> Remove some odd #define void.
> 
> ---
> 
> diff --git a/malloc/malloc.c b/malloc/malloc.c
> index b87280228a0b6e07f5a38e6b45af842fa29c34ac..a7d0f685e16ea91d68d4d82924cb960fe9acb1a0 100644
> --- a/malloc/malloc.c
> +++ b/malloc/malloc.c
> @@ -198,14 +198,6 @@
>      There are several other #defined constants and macros that you
>      probably don't want to touch unless you are extending or adapting malloc.  */
>  
> -/*
> -  void* is the pointer type that malloc should say it returns
> -*/
> -
> -#ifndef void
> -#define void      void
> -#endif /*void*/
> -
>  #include <stddef.h>   /* for size_t */
>  #include <stdlib.h>   /* for getenv(), abort() */
>  #include <unistd.h>   /* for __libc_enable_secure */
> @@ -259,6 +251,15 @@
>  #include <sys/random.h>
>  #include <not-cancel.h>
>  
> +_Static_assert (sizeof (unsigned long) == sizeof (size_t),
> +		"size_t must have same size as unsigned long");
> +_Static_assert (sizeof (void *) == sizeof (size_t),
> +		"size_t must have same size as pointers");
> +_Static_assert (sizeof (void *) == 4 || sizeof (void *) == 8,
> +		"pointers must be 4 or 8 bytes");
> +_Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
> +		"PTRDIFF_MAX is not more than half of SIZE_MAX");
> +

We have verify.h to simplify the _Static_assert usage.

>  /*
>    Debugging:
>  
> @@ -1263,9 +1264,6 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
>  static __always_inline size_t
>  checked_request2size (size_t req) __nonnull (1)
>  {
> -  _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
> -                  "PTRDIFF_MAX is not more than half of SIZE_MAX");
> -
>    if (__glibc_unlikely (req > PTRDIFF_MAX))
>      return SIZE_MAX;
>  
> 



More information about the Libc-alpha mailing list