[U-Boot] C99 and dynamic arrays

Måns Rullgård mans at mansr.com
Wed Mar 13 11:29:01 CET 2013


Tom Rini <tom.rini at gmail.com> writes:

> On Tue, Mar 12, 2013 at 7:22 PM, Simon Glass <sjg at google.com> wrote:
>> Hi,
>>
>> Given that we seem to allow C99 features in U-Boot I wonder if it
>> would be OK to use dynamic arrays in SPL?
>>
>> I am trying to replace:
>>
>> ptr = malloc(size);
>>
>> with:
>>
>> char ptr[size];
>>
>> to avoid use of malloc in SPL. Can I assume that is permitted?
>
> Without knowing the underlying mechanics of how that works, "maybe".

How it works depends on the compiler.  Some compilers implement it by
calling malloc().  GCC uses the stack.

Regardless of how they are implemented, variable-length arrays should,
in my opinion, never be used.  There is simply no way they can be used
safely since no mechanism for detecting failure is provided.  If the
requested size is too large, you will silently overflow the stack or end
up with an invalid/null pointer.  In an environment without full memory
protection, errors resulting from this are very hard to track down.

If the size is somehow limited to a safe value, it is more efficient to
simply allocate this maximum size statically.

-- 
Måns Rullgård
mans at mansr.com


More information about the U-Boot mailing list