Information Zero length arrays or Flexible array members

Discussion in 'PC Hardware and Software' started by BANHAMMER, Sep 13, 2012.

Share This Page

  1. BANHAMMER

    BANHAMMER Teh Almighty BanHammer Staff Member

    Messages:
    5,046
    Likes Received:
    1,434
    Reputation:
    2,993
    [justif]Zero length arrays are commonly used in system programming or otherwise if the size of an array cannot be determined prior to its usage and pointers may not be useful in that situation because of unknown memory space.[/justif]

    Check out the code below.
    Gcc extensions provide such capabilities, but c99 has made provision for FAMs
    Important thing to understand about FAM is that sizeof() operator cannot be used on FAMs.
    Code:
      1 #include <stdio.h>
      2 #include <string.h>
      3 #include <stdlib.h>
      4struct zero_len {
      5        int one;
      6        char two;
      7        unsigned int length;
      8        char empty[]; //<--- this here is Flexible array member
      9 };
    10
    11 int main (void)
    12 {
    13        struct zero_len *new_zero;
    14        struct zero_len *old_zero;
    15
    16        new_zero = (struct zero_len *)malloc(sizeof (struct zero_len));
    17        old_zero = malloc(sizeof(struct zero_len) + strlen("the new string") + 1); // add extra space
    18        printf("%d %d %d %d\n", sizeof(*new_zero), sizeof(new_zero->one), sizeof(new_zero->two),
    19                          sizeof(new_zero->length));
    20        strcpy(old_zero->empty , "the new string"); // this is the assignment
    21        puts(old_zero->empty);
    22        printf("%d %d %d %d\n", sizeof(*old_zero), sizeof(old_zero->one), sizeof(old_zero->two),
    23                          sizeof(old_zero->length));
    24        return 0;
    25 }
    
    For more details on where this idea is used in reality:
    Robert Love's answer to C (programming language): What is the advantage of using zero-length arrays in C? - Quora

    This is GCC link about zero length arrays:
    Zero Length - Using the GNU Compiler Collection (GCC)
     
    JD666 likes this.
  2. fleshfragger

    fleshfragger RAID Rookie

    Messages:
    343
    Likes Received:
    141
    Reputation:
    560
    Its an old C hack to allow flexible arrays. Zero-length arrays did not become legal Standard C until 1999.
     
  3. BANHAMMER

    BANHAMMER Teh Almighty BanHammer Staff Member

    Messages:
    5,046
    Likes Received:
    1,434
    Reputation:
    2,993
    It's not a hack, it's GCC extension and yes FAM were not implemented until C99. Beside at kernel level such things don't matter much.
     

Share This Page