Home > C Programming, C++, VC++ > Careful with sscanf and fscanf

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…

BYTE ByteVar = 0; // Declaration
sscanf( Buffer, "%d", &ByteVar );// Looks innocent right?

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.

Advertisements
  1. Robert Thompson
    January 7, 2010 at 9:18 pm

    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.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: