NASM - get the number of items in the stack

I am trying to figure out how to get the number of elements on the stack by subtracting the sp register with bp. What am I doing wrong? I get a completely wrong result.

MOV bp, 0x7E00 MOV sp, bp PUSH 'A' PUSH 'B' PUSH 'C' POP bx MOV al, bl CALL _printchar POP bx MOV al, bl CALL _printchar MOV bx, sp SUB bx, bp ADD bx, 48 ;To get ascii number MOV al, bl CALL _printchar 

This is the conclusion:

CB.

+5
source share
1 answer

Actually the confusion in the stack is that it is growing.

Compared to most people, the mental image of the stack, the stack with which you work in the assembly, is โ€œturned upside downโ€. The bottom stack has the highest memory address, and the top stack has the lowest. When you push 2 bytes onto the stack, 2 bytes are subtracted from the stack pointer, not added to it. (If you think about it in terms of memory sharing, it's actually safer)

So the result of your SUB was -2, which is equal. in ascii. You cannot just switch operands because the result must go to the first operand, therefore it must be a general register. Instead, change the MOV operations before SUB.

+5
source

All Articles