Parse, Don't Validate (For C)

https://news.ycombinator.com/rss Hits: 11
Summary

“A good programmer is someone who looks both ways before crossing a one-way street.” – Doug Linder Posted by Lelanthran 2025-03-27 “Parse, Don’t Validate” - the long version If you’ve read the original post on “Parse, Don’t Validate” you may have noticed that it focuses primarily on conceptual correctness. Here, I’ll build on that by showing how this technique can be used outside of niche academic languages by demonstrating it in a language that is as practical as it is dangerous - C. In this blog post you will see three techniques of reducing the risk of exploitable errors in C. “Parse, Don’t Validate” - the TLDR version The basic idea is this: Data Comes Into Your System. Your System Processes It. Your first instinct, when your system receives as input an email address (for example), is to perform validateEmail(untrustedInput) and then pass the validated string further into the depths of the system for usage. The problem is that other code deep within the rest of the system is going to also do some sort of validation on the string they just got. Every single function deep within the bowels of the system will still need to validate the input before processing it. I’ll bet good money that the processing functions will attempt to validate their input. Because they’re logically far away from the boundary, they’ll either do it a different way or fail to do it altogether. So instead of this: // Pseudocode if (validateEmail(untrustedInput) != true) { return error; } // Rest of system uses `untrustedInput` Rather do this instead: // Pseudocode email_t theEmail = parseEmail(untrustedInput); if (theEmail == PARSE_ERROR) { return error; } // Rest of system uses `theEmail` This removes any opportunity for errors to creep in within the rest of the system, such as some other code using a different validateEmail function on the untrustedInput, for example. Some conventions for Safety in C. What does this have to do with C strings? Good question. Much to the surprise of, well, ev...

First seen: 2025-07-13 04:53

Last seen: 2025-07-13 14:55