More care is needed when allocating memory in
code intended to run on both GNU and non-GNU systems,
or when a non-GNU replacement allocator is used (see Replacing malloc).
When storage size is small or outlandishly large,
or when storage is allocated for a less-common type,
the POSIX and ISO C standards permit multiple behaviors.
malloc (0)
returns a non-null pointer to a newly allocated size-zero block.
However, IBM AIX is unusual in that a successful malloc (0)
returns a null pointer, and this breaks common code such as the
implementation of xmalloc given in this manual. See Examples of malloc.
Code intended to be portable to IBM AIX can use
p = malloc (size | (size == 0)) instead of p = malloc (size),
or if it does not mind a null pointer on success it can replace the following
if (p == NULL) fatal (...); with
if (p == NULL && size != 0) fatal (...);.
malloc call sets errno,
but ISO C does not require this and non-POSIX implementations
need not set errno when failing.
malloc always fails when size exceeds
PTRDIFF_MAX, to avoid problems with programs that subtract
pointers or use signed indexes. Other implementations may succeed in
this case, leading to undefined behavior later.
malloc (size) returns a pointer that when
converted to an integer is a multiple of alignof (max_align_t).
Some other implementations may align the result only to what is needed for
fundamentally-aligned objects of size at most max (size, 1).
For example, if alignof (max_align_t) is 16 but smaller
fundamentally-aligned objects all have alignment of at most 4,
other implementations of malloc (15) might return
a pointer that is a multiple of 4 but not of 16 or even of 8.
Portable code should therefore use a function like aligned_alloc
if it needs alignof (max_align_t) alignment even for small allocations.
char; all integer types (includingbool);float,double,long double;_Decimal32,_Decimal64,_Decimal128;float _Complex,double _Complex,long double _Complex; all enumerated types; all pointer types; all array types whose element types have fundamental alignment; all struct and union types whose element types all have fundamental alignment and that lack stricter alignment specifiers;va_list(in<stdarg.h>);fpos_t(in<stdio.h>);cnd_t,thrd_t,tss_t,mtx_t,once_flag(in<threads.h>);mbstate_t(in<wchar.h>).
In theory, portable code should not use malloc to
allocate storage containing types not in this list;
it should instead use functions like aligned_alloc.
In practice, though, other implementations generally follow
the GNU C Library’s lead and define only types with fundamental alignment,
and it is generally portable to use malloc to allocate objects
with types defined by the C library.