In the third chapter of the above book, the implementation of the table of atoms is given. In particular, it shows the implementation of the function responsible for adding a new row to the table.
static struct atom { struct atom *link; int len; char* str; } *buckets[2048]; const char* Atom_new(const char* str, int len) { unsigned long h; int i; struct atom *p; assert(str); assert(len >= 0); for (h = 0, i = 0; i < len; i++) h = (h<<1) + scatter[(unsigned char)str[i]]; h %= NELEMS(buckets); for (p = buckets[h]; p; p = p->link) if (len == p->len) { for (i = 0; i < len && p->str[i] == str[i];) i++; if (i == len) return p->str; } p = (struct atom *)malloc(sizeof (struct atom) + len + 1); p->len = len; p->str = (char*)(p + 1); if (len > 0) memcpy(p->str, str, len); p->str = '\0'; p->link = buckets[h]; buckets[h] = p; } scatter is an array of unsigned long scatter[] containing 256 elements In the original, instead of p = (struct atom *)malloc(sizeof (struct atom) + len + 1); p = ALLOC(sizeof(*p) + len + 1) and an explanation is given that
The structure of the structure of the structure of the space structure and the structure of the structure of the structure of the structure.
so the replacement, if I understand correctly, is correct.
Specifically, I can not understand this line
p->str = (char*)(p + 1); What does this shift by one mean? With such a shift, wouldn't the pointer point to memory outside the structure? Isn't it possible to do without this line, since we have allocated memory for the whole structure (including the string) and with the help of memcpy we just copy the string into p-> str?
p->str = '\0'??? The code is written nonsense. Or you incorrectly reprinted. Either this book is a place in the furnace. - AnT