#543 sizeof() on struct containing an array is wrong


With this program:


typedef struct {
unsigned char length;
unsigned char unicode_data[];
} StringDescriptor;

StringDescriptor sd = {
'a', 0, 'b', 0, 'c', 0

unsigned char d = sizeof(sd);


sizeof(sd) should be 7, but sdcc thinks it's 1.

Both the 8051 and Z80 code generation show problems
with this input, but they produce different output.


  • Nobody/Anonymous

    Logged In: NO

    This is invalid code. The compiler shouldn't accept it.

    [tim@pauli /home/tim]$ cat test.c
    typedef struct {
    unsigned char length;
    unsigned char unicode_data[];
    } StringDescriptor;

    [tim@pauli /home/tim]$ gcc -c -Wall -W -ansi -pedantic test.c
    test.c:3: array size missing in `unicode_data'
    [tim@pauli /home/tim]$

  • Scott Bronson

    Scott Bronson - 2003-07-14

    Logged In: YES

    Yes, but this compiles without error: gcc -c -Wall -W
    -std=c99 -pedantic test.c

    BTW, if you add -pedantic, half the code on this planet
    won't compile. :)

    Most compilers allow you to declare a flexible array as a
    one-item array (tt[1]), then overpopulate it. If you do
    this with SDCC, however, it truncates the initialization
    data to one item. I don't know what the standard says about
    this, but it's the only compiler I've ever seen that has
    this behavior.

    Finally, you'll notice that SDCC _does_ support flexible
    arrays, just not when they're members of a struct.

    Food for thought.

  • Erik Petrich

    Erik Petrich - 2003-08-21

    Logged In: YES

    If I add:

    int main(void) {
    printf("sizeof(sd) = %d\n",sizeof(sd));
    printf("sd.length = %d\n", sd.length);

    to your sample source and compile with your suggested

    gcc -c -Wall -W -std=c99 -pedantic test.c

    the output from the program is

    sizeof(sd) = 1
    sd.length = 1

    So I don't see that gcc (version 3.2.2) is interpretting
    this any better.

  • Maarten Brock

    Maarten Brock - 2004-05-03

    Logged In: YES

    What gcc and sdcc do is exactly what's in the C99 spec. It's
    allowed to have an array of unspecified length as last element
    in a struct, but the size of the struct should reflect the size
    with array length 0.

    What sdcc does wrong is allocate only 1 byte for sd.


  • Maarten Brock

    Maarten Brock - 2004-05-26
    • assigned_to: nobody --> maartenbrock
  • Maarten Brock

    Maarten Brock - 2004-05-31
    • milestone: --> fixed
    • status: open --> closed-fixed
  • Maarten Brock

    Maarten Brock - 2004-05-31

    Logged In: YES

    Fixed in SDCCglue.c 1.170, SDCCsymt.c 1.184


Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks