The problem with getline is that malicious input could send a very long line and crash your program due to running out of memory.
The only safe way is to use fgets and check the last character: if it's \n, the line fit; else it didn't and you can either (a) complain and error-out or (b) read the input, character by character, until you find a newline to flush the line since the rest of the input is still on the input stream — but this assumes malicious input even has a newline, so you might not crash, but could be looping forever. You could also check the number of characters read and finally exit in defeat if you've exceeded some arbitrarily large number.
There's no perfect solution when you can't trust your input (which you never should).
The problem with
getlineis that malicious input could send a very long line and crash your program due to running out of memory.The only safe way is to use
fgetsand check the last character: if it's\n, the line fit; else it didn't and you can either (a) complain and error-out or (b) read the input, character by character, until you find a newline to flush the line since the rest of the input is still on the input stream — but this assumes malicious input even has a newline, so you might not crash, but could be looping forever. You could also check the number of characters read and finally exit in defeat if you've exceeded some arbitrarily large number.There's no perfect solution when you can't trust your input (which you never should).
Solid point regarding the OOM/DoS risk, I appreciate the rigorous audit. I'll update the article to reflect this trade-off.