Make zero size allocation result consistent across directives

Chris Johns chrisj at rtems.org
Wed Apr 21 06:32:25 UTC 2021


On 21/4/21 4:07 pm, Sebastian Huber wrote:
> Hello,
> 
> while working on the specification of some memory allocation directives I
> noticed that zero size allocations have no consistent behaviour in RTEMS. For
> example malloc( 0 ) returns NULL and posix_memalign(&p, align, 0) returns in p a
> unique pointer (or NULL if no memory is available). In POSIX zero size memory
> allocations are implementation-defined behaviour. The implementation has two
> options:
> 
> https://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
> 
> https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html
> 
> See also:
> 
> http://devel.rtems.org/ticket/4390
> 
> Linux returns a unique pointer for zero size memory allocations. I tend to use
> this approach as well and would like to remove the
> 
> 
>   /*
>    * Validate the parameters
>    */
>   if ( !size )
>     return (void *) 0;
> 
> in the RTEMS malloc().

For the record FreeBSD shows:

$ cat no-size.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  printf("malloc size 0 = %p\n", malloc(0));
  return 0;
}
$ cc -o no-size no-size.c
$ ./no-size
malloc size 0 = 0x800e16000

Are we too late to make such a change?

What if a user happens to depend on 0 returning NULL?

The FreeBSD jemalloc code has an option to assert if size is 0 which is an
interesting idea.

Chris


More information about the devel mailing list