www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 22807] New: ImportC: Array index is out of bounds for


          Issue ID: 22807
           Summary: ImportC: Array index is out of bounds for old-style
                    flexible arrays.
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: ImportC
          Severity: minor
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: dave287091 gmail.com

The following C code fails to compile, with a compile time array bounds check

// oldarray.c

struct OldFashionedHeader {
    int n; // number of entries in buff
    char buff[1];

int peek(OldFashionedHeader *head){
    if(head->n < 2)
        return 0;
    return head->buff[1]; // Error: array index 1 is out of bounds
`(*head).buff[0 .. 1]`

The above pattern is sometimes seen in old C code and old C apis that predate
the addition of C99 flexible array members. Technically this code is not
strictly correct as it access out of the bounds of its array, but this pattern
can be seen in sqlite, windows APIs (such as the definition of
), and GCC accepts it as a variant of its zero-length array extension (which
also predates flexible array members), as described here:

D code can bypass the check by accessing the .ptr member, but C code isn’t
to do that.

Feb 21 2022