Today I spent way too long debugging my toy compiler.
The tokenizer seemed to work perfectly. GDB showed the expected tokens:
exit
69
;
Yet the generated assembly file was empty.
I checked:
- the parser
- the code generator
- the file writing
- the assembler
- the linker
Everything looked fine. The culprit?
size_t m_ind;
I had forgotten to initialize it. It should have been:
size_t m_ind = 0;
or initialized in the constructor.
The funny part is that tokenize() appeared to work. That's the trap with undefined behavior in C++.
An uninitialized variable doesn't always crash your program. Sometimes it "works" just long enough to convince you the bug is somewhere else.
Today's reminder:
- If you're seeing impossible behavior, suspect undefined behavior.
- DO Initialize your member variables.
- Never trust code just because it worked once.


Top comments (0)