Careful with sscanf and fscanf

If you are not careful while using sscanf and fscanf, you code could lead to stack corruption errors leading to application crash.

Recently when migrating a project in VC6 to VC8, a similar situation arose, I was getting stack corruption errors…

“Run-Time Check Failure #2 – Stack around the variable ‘ByteVar’ was corrupted.”

So I started looking for usage of “ByteVar” in the code being migrated, so a particular innocent looking piece of code got my attention and looked something like this…

[sourcecode language=”cpp”]BYTE ByteVar = 0; // Declaration
sscanf( Buffer, “%d”, &ByteVar );// Looks innocent right?[/sourcecode]

But the problem here is with the format specifier used for a BYTE var, it should be %c, but it’s %d i.e. sscanf reads in 4 bytes instead of 1 byte but the address passed in is of a BYTE. 🙁

In release this works fine and in debug mode above error pops up. Trouble is how to fix this, it’s dangerous to change %d to %c because sscanf will read in only 1 byte instead of four bytes which will result in invalid data being read into other variables. So the safest option IMO is to change the type of “ByteVar” from BYTE to int.

One thought on “Careful with sscanf and fscanf

  1. Actually, this is documented behaviour. If you look at “scanf Width Specification” in the C Runtime Library Reference, you’ll see that the format code “%hd” will cause a number to be read and stored as a byte.

Appreciate your comments...