Is replacing alloca(3) where possible a good thing to do?

Jan Bramkamp crest at rlwinm.de
Wed Sep 14 12:54:46 UTC 2016


On 14/09/16 12:53, twilight wrote:
> Hello,
>
> I again,
> in cddl/* alloca(3) is used very intensively for creating dynamic arrays.
> But, well, it's kinda obsolete and sometimes not safe and portable.
> Is replacing alloca(3) with dynamic arrays a good thing? Or should
> everything be left as it is?
>
> Thanks in advance.

alloca() and VLAs aren't completely interchangeable e.g. alloca() should 
return pointers with the same alignment as malloc while a VLA is just 
correctly aligned for its member type. Some types can't be stored  in 
VLAs without casting e.g. if you want to store an incomplete type like a 
struct ending with a zero sized array you can't put such a struct in a 
union with a char array to allocate space for the array elements. In 
such cases alloca() is easier to read and more portable. You won't 
notice the unaligned accesses on a x86 CPU but they would trap on a 
SPARC or ARM (<= ARMv5). Other CPUs silently round down your unaligned 
pointer to the next natural aligned address.


More information about the freebsd-hackers mailing list