Reverse Engineering for Beginners

(avery) #1

CHAPTER 7. SCANF() CHAPTER 7. SCANF()


7.3 scanf() result checking


As was noted before, it is slightly old-fashioned to usescanf()today. But if we have to, we need to at least check if
scanf()finishes correctly without an error.


#include <stdio.h>


int main()
{
int x;
printf ("Enter X:\n");


if (scanf ("%d", &x)==1)
printf ("You entered %d...\n", x);
else
printf ("What you entered? Huh?\n");

return 0;
};


By standard, thescanf()^4 function returns the number of fields it has successfully read.


In our case, if everything goes fine and the user enters a numberscanf()returns 1, or in case of error (orEOF^5 ) — 0.


Let’s add some C code to check thescanf()return value and print error message in case of an error.


This works as expected:


C:...>ex3.exe
Enter X:
123
You entered 123...


C:...>ex3.exe
Enter X:
ouch
What you entered? Huh?


7.3.1 MSVC: x86.


Here is what we get in the assembly output (MSVC 2010):


lea eax, DWORD PTR _x$[ebp]
push eax
push OFFSET $SG3833 ; '%d', 00H
call _scanf
add esp, 8
cmp eax, 1
jne SHORT $LN2@main
mov ecx, DWORD PTR _x$[ebp]
push ecx
push OFFSET $SG3834 ; 'You entered %d...', 0aH, 00H
call _printf
add esp, 8
jmp SHORT $LN1@main
$LN2@main:
push OFFSET $SG3836 ; 'What you entered? Huh?', 0aH, 00H
call _printf
add esp, 4
$LN1@main:
xor eax, eax


Thecallerfunction (main()) needs thecalleefunction (scanf()) result, so thecalleereturns it in theEAXregister.


We check it with the help of the instructionCMP EAX, 1(CoMPare). In other words, we compare the value in theEAX
register with 1.


(^4) scanf, wscanf:MSDN
(^5) End of file

Free download pdf