4 ms·
It seems so trite, especially in 2023, but please don't use sprintf. It isn't safe in general. (Even snprintf is tricky.)
by guitarbill 3y ago
It seems so trite, especially in 2023, but please don't use sprintf. It isn't safe in general. (Even snprintf is tricky.)
- mkoubaa 3y agoThere are a lot of use cases where "isn't safe" is absolutely irrelevant
- i-use-nixos-btw 3y agoOTOH, in many of the cases where “isn’t safe” IS relevant, the developer believes it isn’t.
- kevin_thibedeau 3y agoBuffer overflows are never irrelevant. You might get away with it until the day it blows up or someone manages to exploit it. Or you could code it correctly the first time.
- fsloth 3y ago"It isn't safe in general" Disagree. Use whatever is the most simple and boring option for the problem's solution. Also, the standard library has so much stuff that will give you pain in runtime, that avoiding sprintf really is not relevant. I don't know what "Safe" means in general in the scope of C++. If there is a memory corruption, my program will crash. Then I will compile it with C++ debug runtime, which will pinpoint the exact location that caused the memory leak. Then I fix the leak. Not using sprintf will not result in code that would not have memory leaks. C++ in total is unsafe. You need to write code and have production system that foremost takes this into account. You can't make C++ safe by following dogma of not using functions with possible side-effects. There is a very hight chance your fall-back algorithms themselves will leak memroy anyway. The only way to write 'as non-leaky' C++ as possible is to make the code as simple, and easy to reason about as possible, and to have tooling to assist in program validation. This requirement is much more important than avoiding some parts of standard library. Use static checkers, use Microsoft's debug C runtime, use address sanitizers, etc. If you know some parts of you standard library are broken then ofc avoid them. But what can be considered "broken" really depends what one is trying to achiece, and which platforms one is targeting.
- deleted 3y ago[deleted]
- consoomer 3y agoYOLO
- 38 3y agosaying "dont use" something isn't really actionable, unless you give a safe alternative.
- thiht 3y agoAnd explain why it’s not safe too
- jjnoakes 3y agoThe safe alternatives are in the article.
- cozzyd 3y agoasprintf is often a better choice if you're heap allocating anyway. For a static or stack buffer, obviously snprintf, unless you know the maximum possible length won't exceed (which you often do....).