Assembly Language for Beginners

(nextflipdebug2) #1

1.9. SCANF()


So what happens here? xis not uninitialized and contains some random noise from local stack. When
scanf()called, it takes string from user, parses it into number and tries to write it intox, treating it as
an address in memory. But there is a random noise, soscanf()will try to write at random address. Most
likely, the process will crash.


Interestingly enough, someCRTlibraries in debug build, put visually distinctive patterns into memory just
allocated, like 0xCCCCCCCC or 0x0BADF00D and so on. In this case,xmay contain 0xCCCCCCCC, and
scanf()would try to write at address 0xCCCCCCCC. And if you’ll notice that something in your process
triestowriteataddress0xCCCCCCCC,you’llknowthatuninitializedvariable(orpointer)getsusedwithout
prior initialization. This is better than as if newly allocated memory is just cleared.


1.9.3 Global variables


What if thexvariable from the previous example isn’t local but a global one? Then it would have been
accessible from any point, not only from the function body. Global variables are consideredanti-pattern,
but for the sake of the experiment, we could do this.


#include <stdio.h>


// now x is global variable
int x;


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


scanf ("%d", &x);

printf ("You entered %d...\n", x);

return 0;
};


MSVC: x86


_DATA SEGMENT


COMM _x:DWORD
$SG2456 DB 'Enter X:', 0aH, 00H
$SG2457 DB '%d', 00H
$SG2458 DB 'You entered %d...', 0aH, 00H
_DATA ENDS
PUBLIC _main
EXTRN _scanf:PROC
EXTRN _printf:PROC
; Function compile flags: /Odtp
_TEXT SEGMENT
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG2456
call _printf
add esp, 4
push OFFSET _x
push OFFSET $SG2457
call _scanf
add esp, 8
mov eax, DWORD PTR _x
push eax
push OFFSET $SG2458
call _printf
add esp, 8
xor eax, eax
pop ebp
ret 0
_main ENDP
_TEXT ENDS

Free download pdf