From mboxrd@z Thu Jan 1 00:00:00 1970 From: =?iso-8859-1?Q?M=E5ns_Rullg=E5rd?= Date: Wed, 13 Mar 2013 20:16:28 +0000 Subject: [U-Boot] C99 and dynamic arrays In-Reply-To: <5140C743.3030508@wwwdotorg.org> (Stephen Warren's message of "Wed, 13 Mar 2013 12:36:51 -0600") References: <5140C743.3030508@wwwdotorg.org> Message-ID: List-Id: MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit To: u-boot@lists.denx.de Stephen Warren writes: > On 03/13/2013 12:03 PM, M?ns Rullg?rd wrote: >> Simon Glass writes: >> >>> Hi Mans, >>> >>> On Wed, Mar 13, 2013 at 3:29 AM, M?ns Rullg?rd wrote: >>>> Tom Rini writes: >>>> >>>>> On Tue, Mar 12, 2013 at 7:22 PM, Simon Glass 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. >>> >>> I suppose we could check the available stack space. However I don't >>> really see a clear stack bottom in U-Boot - I think it is set up to >>> grow downwards as much as needed. I can certainly add sanity checks on >>> the input values. >> >> There is no way to check stack usage from C. >> >>>> If the size is somehow limited to a safe value, it is more efficient to >>>> simply allocate this maximum size statically. >>> >>> Yes although this does waste BSS. >> >> Sorry, I meant a statically sized stack allocation. > > But, there's also no way to detect failure in that case either. No, but there is an obvious upper bound to the frame size. Absent recursion, a static analysis tool can find the maximum stack space required starting from a given point, but only if each function uses a fixed amount. -- M?ns Rullg?rd mans at mansr.com