Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

confused about stack, and

Status
Not open for further replies.

Beholder2

Technical User
Sep 27, 2004
31
US
Hello I'm attempting to learn to use assembly routines through Qbasic, I found the following example from a tutorial which I followed. It's a simple program that will add four to a number placed on the stack by Qbasic. But I cannot understand why He used 'mov bp,sp' what does that mean? What does 'mov the stack pointer to base pointer' actually say? I figured to access something on the stack you'd use just the stack pointer, and why doesn't he use SS in this working example?
what exactly does SP point to then? Can anyone explain the stack and the methods of accessing things on it, thanks I really appreciate any help.
------------------------------------------------------------
.model medium, basic
.stack 200h
.386
.code

public AddFour

; Our stack:
; Number 6
; QB Seg 4
; QB Off 2
; BP 0

AddFour proc
push bp
mov bp, sp
mov ax, [bp+6]
add ax, 4
pop bp
ret 2
AddFour endp

end
-----------------------------------------------------------
 
sp holds the stack location accessed on pushing and popping. The stack usually holds local variables (and function parameters, which are not so terribly dissimilar), return addresses from called procedures, and anything that's been pushed and not yet popped.

Normally local variables are referenced via bp, which is why procedures (functions) tend to start with this push bp; mov bp, sp thing. What this does is saves the local variable reference point of the previous function/procedure (on the stack itself), and sets up a new reference point.

You could, in theory, reference local variables via sp (in which case you're right, you don't need these instructions). But it would be trickier and more likely to go wrong in the hands of a dodgy programer or compiler. One reason is that every time you pushed something, you'd have to remember that all the local variables were now at a different offset! Another is that you can currently get away with pushing a few things and never popping them, because at the end of a function/procedure, you restore sp from bp, before popping the old bp, and then carrying out the ret instruction. Restoring the old sp from bp cleans up any pushes that weren't popped, not that I'd ever encourage that sort of behaviour.

Note that my explanation is biassed because I did most of my assembly programing in conjunction with Pascal, and Pascal and C calling conventions differ slightly. The general principles of stack-frame structures and using bp are much the same.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top