Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The code for that blog post is fragile in an interesting way. Its safety and security depend on a subtle invariant: that the 'word_regex' does not match a string containing any non-ASCII character. If requirements changed so the regex could match a non-ASCII character, then one of the 'c' chars could have a negative value other than -1. https://en.cppreference.com/w/cpp/string/byte/tolower says "If the value of ch is not representable as unsigned char and does not equal EOF, the behavior is undefined", so executing std::tolower(c) would trigger undefined behavior, i.e. a safety and security bug.

This fragility is not at all obvious in the code. It is easy to imagine someone making that kind of change to word_regex and introducing a theoretical security bug that no compiler or static checker is going to pick up (AFAIK). Of course the severity of the bug in practice depends on what std::tolower does in that undefined-behavior situation (which may depend on the run-time locale setting).

I think the author's example actually illustrates the C++ safety problem pretty well. You write a program that looks safe and actually is safe, but slightly different code which looks just as safe is not. You're tiptoeing through a minefield.



In at least some locales tolower segfaults under that condition, in glibc at least.

(before anyone says that ‘in reality it’s probably fine’)


I would love to know an example of that.



That quotes a glibc comment "we also support negative `signed char' values for broken old programs" which means the OP code is in fact going to behave OK with glibc, providing that "support for broken old programs" is never removed.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: