[Issue 22807] New: ImportC: Array index is out of bounds for old-style flexible arrays.

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Feb 22 06:24:39 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=22807

          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 at puremagic.com
          Reporter: dave287091 at gmail.com

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

// 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
https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapcoreinfo
), and GCC accepts it as a variant of its zero-length array extension (which
also predates flexible array members), as described here:
https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

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

--


More information about the Digitalmars-d-bugs mailing list