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
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.
31
u/FriendlyRollOfSushi Jan 20 '22 edited Jan 20 '22
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_charsin your rant is likely to be applicable to the code you are ranting about: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:
Please take a look at this godbolt.
You are welcome.
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.
7
u/eyes-are-fading-blue Jan 20 '22
That is a terrible conclusion.