Search code examples
assemblyx86stacknasmstack-pointer

Using the esp register


I was trying to understand how to use the stack with assembly and in my attempt I came across the following code in one of the questions in SO, namely:

push    ecx

mov eax, 4
mov ebx, 1
mov ecx, result
mov edx, result_len
int 0x80

mov eax, 4
mov ebx, 1
mov ecx, esp
add [ecx], DWORD 48
mov edx, 2
int 0x80

In this case ecx, is holding a number and the author is displaying the number by (correct me if I am wrong!) first moving the stack pointer to ecx and then converting the number to ascii character by adding 48 to the memory address where ecx is pointing. Would he have been able to do the same thing by "pop ecx" and then convert to ascii? I do not quite understand why the author is proceeding in this way. Any help would be appreciated.


Solution

  • Would he have been able to do the same thing by "pop ecx" and then convert to ascii?

    No. The sys_write system call, needs a pointer to the string to print. By pushing ecx onto the stack, you create a pointer (address) in esp.