Continuing from last nights post on securing code with coffee and sleep, I am following up with with more tips of coding that seem to be neglected by the text books.
I will get to picking on others (many others) in time, but right now I am working on and and up to errors in Chapter 4 of the same book which is:
“Teach Yourself C in 21 days” by SAMS.
As noted yesterday, day 4, has a type and run as they call it. You enter the code even if you do not understand all of it yet.
I have modified the code as is listed below. I have not tidied this such that printf() has been replaced and there are many other things I could do to improve this, but the point is that a simple change can make this more resilient.
This compiles well enough and we can see the results in figure 2.
Figure 2: Type and Run “Find_nbr.c” now accepting valid data
I do not see the code changes as too onerous. The “Type and Run” was not designed to have students understand this day, but as a prelude in any event.
Figure 3: We can handle non-numerals now and over large values!
Again, why must we teach poor coding skills and then have to relearn secure coding?
C has NO native error handling and bounds checking. You as the programmer have to tell C just what it needs to do and it will try to do what you want no matter how illogical this can be. As such, you need to defend C from bad code. You need to make sure that any input is validated first.