Whenever I’m writing C code I am amazed that we have to keep track of things like array lengths and string terminators. It’s no wonder poor coders create weird bugs, like this one I found in my work code for storing atom names (like chlorine-1, carbon-2, etc).
char names[MAX_NAMES][6]; int num_names, i; for(i=0; i < num_names; i++) { printf("(%d) %s\n", i, names[i]); }
This is what I see:
(0) CL1 CL2 C2 (1) CL2 C2 (2) C2 (3) CD2 N2 (4) N2 ...
WTF? Turns out there are exactly three spaces around each of those strings, making the 3-character names overflow. That’s what happens when you use strcpy on strings that are too short to contain the result.