boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

340-struct-char-array-string-init.c (1569B)


      1 /* tests/cc/340-struct-char-array-string-init.c
      2  *
      3  * Regression: a char[N] array that is a *struct field* or *array
      4  * element* initialized by a string literal must be encoded as the
      5  * string's BYTES, not a pointer to the string pool. This is the shape
      6  * of tcc's ArHdr archive-header template (static struct of char[]
      7  * fields); mis-encoding it as pointers produces corrupt `.a` files.
      8  */
      9 
     10 typedef struct { char a[16]; char b[6]; char c[6]; char e[2]; } Hdr;
     11 
     12 /* static (global) struct — bare and braced string field forms. */
     13 static Hdr gbare  = { "/x", "0", "0", "`\n" };
     14 static Hdr gbrace = { {"/x"}, {"0"}, "0", "`\n" };
     15 
     16 /* array of char[] strings, each element a string literal. */
     17 static char rows[3][4] = { "ab", "cd", "ef" };
     18 
     19 static int check(const Hdr *h) {
     20     if (h->a[0] != '/' || h->a[1] != 'x' || h->a[2] != 0) return 1;
     21     if (h->b[0] != '0' || h->b[1] != 0)                   return 2;
     22     if (h->c[0] != '0' || h->c[1] != 0)                   return 3;
     23     if (h->e[0] != '`' || h->e[1] != '\n')                return 4;
     24     return 0;
     25 }
     26 
     27 int main(void) {
     28     /* local struct with char[] string fields */
     29     struct { char a[8]; char b[4]; } loc = { "hello", "wx" };
     30 
     31     if (check(&gbare))  return 10;
     32     if (check(&gbrace)) return 20;
     33 
     34     if (rows[0][0] != 'a' || rows[1][0] != 'c' || rows[2][1] != 'f') return 30;
     35     if (rows[0][2] != 0) return 31;   /* zero-padded tail */
     36 
     37     if (loc.a[0] != 'h' || loc.a[4] != 'o' || loc.a[5] != 0) return 40;
     38     if (loc.b[0] != 'w' || loc.b[1] != 'x' || loc.b[2] != 0) return 41;
     39 
     40     return 0;
     41 }