3 ms·
I'm a beginner C programmer, maybe you can share your experience with me. I've found bugs in libraries where sprintf was used instead of snprintf and it caused
by michaelt 13y ago
I'm a beginner C programmer, maybe you can share your experience with me.
I've found bugs in libraries where sprintf was used instead of snprintf and it caused crashes. So I know from experience of cases where snprintf was a better choice than sprintf. And I've certainly coded a few off-by-one errors in my time so I can sure understand it's easy to get the destination buffer size wrong!
I'm not doing anything performance-critical with strings. Under what circumstances should I use sprintf instead of snprintf and what benefits will I see?
- orangeduck 13y agoIf you understand the difference between snprintf and sprintf, what trouble it can cause, and where to use it, it sounds like you're already doing great. What would be bad was if you had the blind notion that "snprintf is good" and "sprintf is bad" without knowing why. As for an example of when you might want to use sprintf. If you compile to C89 (ANSI) snprintf isn't included in the standard so you're left with sprintf if you want your code to be portable. A better example is strcpy though. A function which is completely normal and safe when used correctly, but someone with the wrong idea might use strncpy as a "safer" version and cause themselves more trouble for not knowing what is going on. As if to prove my point you can see someone advocating this exact thing in another comment tree in this thread. They've probably heard from someone that the "n" version of functions are safe. If they'd actually looked into it they'd realize strncpy doesn't do what you might think.