I need to create a function that swaps the value of &x with the value of &y (meaning swap *(&y) and *(&x).
Swap:
push EBP
mov EBP,ESP
You don't actually reserve memory on the stack that you use when you access a dword at [EBP-4]. It can get overwritten by things like interrupt routines, signal handlers, asynchronously called procedures, whatever applies in your OS.
The code should be like this instead:
swap:
push EBP
mov EBP,ESP ; make a traditional stack frame
sub ESP, 4 ; reserve memory for a local variable at [EBP-4]
mov EBX, [EBP+12] ; ebx = &x
mov EAX, DWORD [EBX] ; eax = x
mov DWORD [EBP-4], EAX ; [ebp-4] = eax = x
mov EDX, [EBP+8] ; edx = &y
mov EAX, DWORD [EDX] ; eax = y
mov DWORD [EBX], EAX ; *&x = y
mov EAX, DWORD [EBP-4] ; eax = x reloaded from the local
mov DWORD [EDX], EAX ; *&y = x
leave ; remove locals (by restoring ESP), restore EBP
ret
Also, make sure that you're passing as parameters the addresses of the variables x
and y
, not the values of the variables. push x
+push y
will pass the addresses of x
and y
in NASM but they will pass values of x
and y
in TASM and MASM.