r/cpp • u/pumpkin_seed_oil • Jan 20 '22
PSA: avoid using stdlib.h, use their stl equivalents
Feel free to delete this, i just have to rant
I just debugged an issue at work caused by strtol in some legacy code. strtol converted, errno always returned ERANGE for seemingly valid values that shouldn't overflow or underflow.
The issue: strtol doesn't clear errno and it wasn't done before strtol and the original author of the code didn't clear it himself. All conversions tested true for ERANGE
You know what function already does that for you? std::stod
Conclusion: don't use the C standard lib functions in C++ if you don't know how they work
rant over
31
u/FriendlyRollOfSushi Jan 20 '22 edited Jan 20 '22
Doesn't read the docs for a 40-years-old function.
Rants about people not using
std::stodin "legacy code", whilestd::stodwas only introduced in 2011, and there are many codebases that only recently converted.
Suggests
std::stodin 2022, five years after we gotstd::from_charswhich is superior in every way.
Look, I don't know how to break the news for you, but no matter how you look at it, you are a part of the problem. Every excuse you can possibly have for not suggesting std::from_chars in your rant is likely to be applicable to the code you are ranting about:
The standard is too new?
Didn't have time to read about every single addition to the library?
Need to support old toolchains for a few more years?
Your reviewers don't approve "new stuff"?
Your manager asked you to avoid pioneering stuff 2 weeks before the big release?
Too tired?
Need coffee?
Force of habit?
All of these excuses work.
Please remember how important everyone's mental health is. By becoming the guy who rants at their colleagues on a public resource just to vent, you are stressing out the people who read your rant. It's not even a zero sum game (you lose some stress, they gain some stress), because of how many people will read this post.
Oh, and let me help you with one more bug:
The issue: strtol doesn't clear errno and it wasn't done before strtol
You know who already does that for you? std::stod
Please take a look at this godbolt.
You are welcome.
2
8
u/zambele Jan 20 '22
Library functions are not supposed to set errno to zero. See https://man7.org/linux/man-pages/man3/errno.3.html.
4
u/ompomp Jan 20 '22
Was that code checking errno even though strtol didn't return that there was an error, i.e. LONG_MIN/LONG_MAX? Only check errno if there's an error.
3
u/adnukator Jan 20 '22
If you don't clear errno before calling strtol, how can you tell whether you've passed the *MIN/*MAX values as strings or that you've really passed a too large value?
7
13
u/Jardik2 Jan 20 '22
I think it is pretty known that most of the function which set errno on failure don't clear it on success and it is up to the caller. strtol is not anything exceptional to this.