April 21, 2006
Band-Aid Safety
The first rule of shop safety is "keep the soft parts away from the whirly parts." If you get your finger tangled up with a saw blade, it's not much comfort to know that you've got a box of band-aids in the medicine cabinet. You have to pay attention, so that accidents don't happen. Unfortunately, the buzz in the programming community about "safety" focuses on treating the results of accidents instead of avoiding them.
If you call strcpy with a buffer that's too short, you're in trouble. That's the kind of thing that malicious applications take advantage of in operating systems and browsers. The solution isn't to rewrite strcpy to take an additional argument that gives the size of the buffer, so that it can refuse to copy too many characters. It's to rewrite the code that calls it to ensure that the buffer is large enough.
There's a discussion on one of the C++ newsgroups about requiring default initialization of class members that aren't listed in the constructor initialization list, to make initialization "safer." There's also a suggested added syntax for saying that you don't want a member initialized. Apparently the thinking is that initializing something to the wrong value is better than not initializing it. Either way, though, it's a mistake, and mistakes need to be fixed.
In both cases, the right way to approach the problem is to design the application so that these errors don't occur. Check the length of an input string when it comes in, and if it's too long, reject it. Review constructors to make sure that they properly initialize members that require initialization. That's your responsibility as a professional programmer. Write correct code, and you won't have to worry about adding safety hacks.
Posted by Pete Becker at 10:21 AM Permalink
|