Posts Tagged ‘bugs’

Careful with sscanf and fscanf

August 1, 2008 1 comment

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.

Variable value is always’s zero, no matter what you do!

May 8, 2008 3 comments

Recently a friend of mine (sitting just behind me) had a strange problem. I wrote an inline function which was like…

void SetBlah( const bool IsBlah ) { m_IsBlah = IsBlah; }

Now he was using this function since we work for the same project! So he had a value 1 for IsBlah when calling this function but no matter what he did m_IsBlah always had the value zero!

He spent half a day trying to solve this issue, I too joined him in this venture. We thought it has got something to do with inlining the function call so we made it non inlined but this didn’t solve the issue. No matter what we did still the value was zero, we tried rebuilding the project but no effect whatsoever.

I tried running the code on my machine and it was fine, working as it should be!

So in the end I found out the problem? But before I post the answer here, any idea what could be the reason?


He had a statement in his watch window like…

theStaticLongNameObject.m_IsBlah = 0;

This expression prevented the value from changing. Also we can’t see the full expression in watch window because of the variable’s long name! 🙂

%d bloggers like this: