variant length array?

Rajat Sharma fs.rajat at gmail.com
Tue Apr 5 16:23:56 EDT 2016


On Tue, Apr 5, 2016 at 1:00 PM, Bjørn Mork <bjorn at mork.no> wrote:
>
> "Robert P. J. Day" <rpjday at crashcourse.ca> writes:
> > On Tue, 5 Apr 2016, Wenda Ni wrote:
> >
> >> Hi all,
> >>
> >> I come across the following code in a kernel module code. It defines
> >> an array whose length is variant at runtime, depending on the actual
> >> inputs. It seems that kernel compiler supports this, which is
> >> obvious an error in the standard ANSI C. Do I have the correct
> >> understanding on it?
> >>
> >> Thank you.
> >>
> >>
> >> u32 rxe_icrc_hdr(struct rxe_pkt_info *pkt, struct sk_buff *skb)
> >> {
> >>          ...
> >>          int hdr_size = sizeof(struct udphdr) +
> >>                  (skb->protocol == htons(ETH_P_IP) ?
> >>                  sizeof(struct iphdr) : sizeof(struct ipv6hdr));
> >>          u8 tmp[hdr_size + RXE_BTH_BYTES];
> >>          ...
> >> }
> >
> >   pretty sure "sizeof" can be calculated at compile time so i don't
> > see a problem here.
>
> Yes, but skb->protocol is variable and sizeof(struct iphdr) !=
> sizeof(struct ipv6hdr)).  Is the compiler smart enough to just use the
> largest possible value?  The logic here is pretty similar to a union,
> which it of course wouldn't have any problems calculating the size of.
>
>
> Bjørn
>
> _______________________________________________
> Kernelnewbies mailing list
> Kernelnewbies at kernelnewbies.org
> http://lists.kernelnewbies.org/mailman/listinfo/kernelnewbies


It is actually a variable length array on stack. BTW nothing fancy
about kernel compiler, its GCC extention.
https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

-Rajat



More information about the Kernelnewbies mailing list