TCC – string index from char str[1] to str[len]

Check TokenSym declaration firstly, TokenSym is to store a single token info.

1
2
3
4
5
6
7
8
9
10
typedef struct TokenSym {
    struct TokenSym *hash_next;
    struct Sym *sym_define; /* direct pointer to define */
    struct Sym *sym_label; /* direct pointer to label */
    struct Sym *sym_struct; /* direct pointer to structure */
    struct Sym *sym_identifier; /* direct pointer to identifier */
    int tok; /* token number */
    int len;
    char str[1];
} TokenSym;

when malloc memory, it will alloc TokenSym+len.

1
ts = tcc_malloc(sizeof(TokenSym) + len);

the later on, memcpy copy str with len to str memory.
Of course, str[1] will be out of range, but extra len memory is appended.
therefore, str[1] is expanded to str[len].

This is very popular within TCC’s struct declaration.

1
2
memcpy(ts->str, str, len);
ts->str[len] = '\0';