Nuts and bolts
Joel Spolsky wrote an article a while back on why it is important to know how computers work at the low level even when programming in a high level language. I came across an example today of how important that is. Have a look at this MFC code:
try
{
CString query;
query.Format(_T("SELECT blah,something FROM mytable\\n")
_T("WHERE itemid=%d AND NOT defleted"));
getDatabaseConnectonPtr()->ExecuteSQL(query);
}
catch(DBException ex)
{
MessageBox(ex.getMessage(), _T("Database error"), MB_OK);
}
OK, the first error is I mistyped the word deleted in my SQL query but instead of throwing up a message box as you’d expect, the application CRASHED with an unhandled exception error. But as you can see, I do have an exception handler so what gives ?!
Have you spotted it yet? It turned out to be the %d token in the format string. I haven’t given it a value. This caused the stack to become corrupted and when the database object threw a DBException, it did not have a valid stack frame for the exception processing. There are thousands of lines of code in my app and I’ve just wasted a whole freakin’ hour finding this bug but I probably never would have worked it out if I did not know how the exception mechanism worked and how C++ uses the stack to pass parameters.
Then again, this kind of thing would never happen if I was writing in Java.
