Why you should never use sprintf

21 Oct 2008

I'm quite convinced a lot of people just should not be coding C at all after reading this discussion from Joel On Software. And this one has some serious security problems. If the dude implemented some of them, I'm sure his app server is now a spam bot.

Anyways, never use sprintf or it's more horrible variant vsprintf functions. You will have a buffer overrun and then you will cry. Using snprintf take almost no more work and is always safe.

Yes this code is technically ok:

char buf{100];
sprintf(buf, 'this is a message');

You are so smart you counted the length of your message, and made a buffer than can hold it. Good for you.

There are compilers, static analyzers, runtime analyzers, call graph analysis, heap profilers, but I have a temporal analyzer that can see into the future and in some 100 line patch, that will come in right before code freeze which part of a critical feature my boss is ranting and raving about that must go live now this snippet will show up in the patch:

<<< sprintf(buf, 'this is a message');
----
>>> sprintf(buf, 'this is a message. User input was %s", input);

Looks great! I approve it, and bam!, I'm in my bosses office explaining why we had to rollback a release at prime time and had 30 minutes of downtime.

Was this the future or the past? The temporal analyzer isn't always clear. The point is do not use sprintf. It's not about how smart you are, it's how dumb the next guy is or rather how stressed out there are while on deadline

Replacing sprintf with snprintf is probably a day job for someone and then it's done. Depending on your code, it might just be a clever regexp.

Keep your code clean, by preventing it from being re-entered. Future versions of gcc will have a new warning flag -Wdisallowed-function-list=sym,sym,.... Failing that you'll need to write a scanner (I'm working on one) to do it manually. This will prevent anyone doing this to begin with.