Question

How do I write an x86 assembly recursion function

Asked by: Fang1964

How do I write an x86 assembly function that recursivly calculates exp(2,n) ie 2^n using the stack to pass n.

Please note the code below is stuck in a loop only run in your debugger, plus is is not doing the require calculation yet i am still trying to get the stack working as it iterates through the formula.

.model small ; Use the small memory model
.stack 300h  ; Include a stack segment
.data
.code
start:
    push 4
    call factorial
    add sp, 4
    mov ax, bx
    mov ax, 1
    ;int 0x80
    
;.type factorial, @function
factorial:
        push bp
        mov bp, sp
        
        mov ax,[bp+8]
        cmp ax, 1
        je end_factorial
        
        dec ax
        push ax
        call factorial
        mov bx, [bp+8]
        mul ax
        
        end_factorial:
        mov bp, sp
        pop bp
        
        ret
 
end start
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-05-11 at 18:53:48ID23393434
Tags

intel

,

Assembly

Topic

Assembly Programming Language

Participating Experts
1
Points
500
Comments
55

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. x86 assembly book?
    Hi, Can anybody recommend a good book on learning x86 assembly that is reasonably modern in style and goes through the basics with good examples of working programs to try? Thanks.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Fang1964Posted on 2008-05-11 at 19:03:28ID: 21544269

Help will be much appreciated.

 

by: Infinity08Posted on 2008-05-12 at 00:42:13ID: 21545163

First of all : why did you call the function factorial ? Did you base the code on some recursive function that calculates the factorial ? You didn't change much ... Are you trying to implement a factorial function ?


I would suggest you first write down the algorithm you want to use in pseudo code. How would you approach calculating 2^n recursively ?

 

by: Fang1964Posted on 2008-05-12 at 02:24:44ID: 21545492

yes i have found some similar programs and trying to modify them. ok will do. However my main issue has been using the stack.

 

by: Infinity08Posted on 2008-05-12 at 02:33:27ID: 21545511

>> ok will do.

Post the algorithm you intend to use here, and I will have a look at it :)


>> yes i have found some similar programs and trying to modify them.

That's not the best idea. You should write the algorithm first, and then try to implement that specific algorithm. You can use other recursion code as a guideline for how recursion works, but don't try to modify existing code that is unrelated. You'll only make it harder on yourself, and will probably be left with something that doesn't work, because it's a mix of two different algorithms.


>> However my main issue has been using the stack.

What issue do you have with that.

 

by: Fang1964Posted on 2008-05-12 at 03:24:15ID: 21545677

get n from user
a=1
while n > 0
a = a * 2
n = n - 1
loop
exit

result = a
-------------------------------------------
storing and retrieving data using this format
mov ax, [bp+4]

 

by: Infinity08Posted on 2008-05-12 at 03:26:38ID: 21545689

That looks good, except that it's an iterative algorithm, not a recursive algorithm.

So, how would you make it recursive ?

 

by: Fang1964Posted on 2008-05-12 at 03:30:07ID: 21545699

calling itself

 

by: Infinity08Posted on 2008-05-12 at 03:31:23ID: 21545705

>> calling itself

I meant : re-write the algorithm to make it recursive - you don't need to make a lot of changes - simply replace the loop with recursive calls :)

 

by: Fang1964Posted on 2008-05-12 at 03:32:43ID: 21545711

so calling the function has to result in doubling it input

 

by: Infinity08Posted on 2008-05-12 at 03:34:23ID: 21545721

>> so calling the function has to result in doubling it input

Yes. Except if the input is a certain value which signifies the end of the recursion. What value ?

Can you write out the new algorithm ?

 

by: Fang1964Posted on 2008-05-12 at 03:41:41ID: 21545750

call power(n)

_power(n)
if n=0              ; cmp ax,0
exit
                       ; mov bx, n?
a= n * 2          ; mul ax
return a           ; ret

 

by: Fang1964Posted on 2008-05-12 at 03:44:56ID: 21545760

call power(n)

_power(n)
if n=0              ; cmp ax,0
exit
                       ; mov bx, n?
a= n * 2          ; mul ax
n=n-1
if n > 0
power(n)
return a           ; ret

 

by: Infinity08Posted on 2008-05-12 at 03:50:35ID: 21545779

This part :

>> a= n * 2          ; mul ax
>> n=n-1
>> if n > 0
>> power(n)

still needs some tuning ... n * 2 has no value ... n is just there to indicate how many times the function should be called recursively.

And you should make good use of the value returned by the recursive function call :

        power(n)

 

by: Fang1964Posted on 2008-05-12 at 04:45:27ID: 21546006

isnt n the number that is used as the power of 2?

i am trying to work it out

 

by: Infinity08Posted on 2008-05-12 at 04:50:46ID: 21546039

>> isnt n the number that is used as the power of 2?

Yes.


Take a look at the iterative algorithm :

>> while n > 0
>> a = a * 2
>> n = n - 1
>> loop

You used n as the number of iterations (which is correct). When transforming the iterative algorithm to a recursive algorithm, n becomes the number of times that the function is called recursively.


>> i am trying to work it out

If you want, you can show your progress here. As well as your doubts, questions, etc. I'm here to help you :)

 

by: Fang1964Posted on 2008-05-12 at 07:37:02ID: 21547354

i got it working in c.
now the real challenge convert that to assembly

#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>

int power(int x, int n);

void main()
{
      int target;
      cout << "enter desired power";
      cin >> target;
      for (int n = 0; n < (target+1); n++)
            cout << "2 to the power " << n << " is " << power(2, n) << endl;
      //return 0;
}

int power(int x, int n)
{
      if (n < 0)
      {      cout << "Illegal argument to power.\n";
            exit(1);
      }
      if (n > 0)
            return(power(x,n-1) * x);
      else  //n=0
            return(1);


}

 

by: Infinity08Posted on 2008-05-12 at 08:14:56ID: 21547680

Did you write this yourself ?

It's not valid C or C++, and it was written for generic powers, not just powers of 2.


Anyway, the algorithm is good. So, you can just translate it to assembler code one line at a time. Do just the power function for now, and leave out the error checking. Just the core algorithm.

 

by: Fang1964Posted on 2008-05-12 at 08:28:43ID: 21547817

yes i did, i made it do generic power because that might be next, i did have power(2,n) = power(2,n-1)*2 n>0 from the question. I have been trying to work it out but we have to use the stack and do it in standardised function calls. i am still lost but i feel abit closer.

 

by: Infinity08Posted on 2008-05-12 at 09:13:03ID: 21548199

>> i am still lost but i feel abit closer.

Good. I'll guide you along until you get there :)

So, you have an algorithm now. Try to start putting that in assembler code like I suggested in my previous post.

You can use the factorial code you posted earlier as a guideline.



Can you post the assignment ? So that I get a better idea of what the intent is ?

 

by: Fang1964Posted on 2008-05-12 at 09:33:14ID: 21548384

i need sleep on it now it's 2.30am, will continue tomorrow. Thanks for your help so far.

 

by: Fang1964Posted on 2008-05-12 at 16:30:35ID: 21551274

sorry i got distracted by

>>You can use the factorial code you posted earlier as a guideline

here are the questions
Question 1

Write an assembly language function that uses recursion to produce exp(2,n) i.e. . Pass the parameter  on the stack and return the result in an appropriate register. Make sure the function conforms to the standard.

Hint : Try writing a C function to do it. Then convert the logic of the C function into assembly language. The recursive equation for exp(2,n) are
exp(2,n) = exp(2,n-1)*2 n>0
exp(2,0) = 1

Question 2

Modify your code for reading in the number n, so that it is now a function according to the standards illustrated in the notes. Call the function readnum. Type in the example writenum function and test to see that it works with readnum and writenum. Create a program that reads in a number and writes out 2 to the power of the number read in.

 

by: Fang1964Posted on 2008-05-12 at 16:31:56ID: 21551279

;            Standardisation Example 2
    ;
    ;         This code shows how to set out standardised
    ;         function calls suitable for use with C and any
    ;         language that passes parameters by value.

              .
              .
              .
              call   readnum       ; Read in a number (to ax)
              mov    [bp-2], ax    ; Save value on stack
              call   newline       ; Start on a new line
              mov    ax, [bp-2]    ; Get value off the stack
              push   ax            ; Setup first (and only) parameter
              call   writenum      ; Write the number out
              add    sp, 2         ; Clean up the stack (2 bytes used)
              .
              .
              .
  writenum:   push   bp            ; Function entry sequence
              mov    bp, sp
              sub    sp, 2         ; Leave space for a local variable
              mov    ax, [bp+4]    ; Get first argument off the stack
              mov    dx, 0         ; Clear high order 16 bits
              mov    bx, 10        ; Store 10 for divide operation
              div    bx            ; Divide dx/ax by bx (10)
              mov    [bp-2], dx    ; Store number to display on stack
              cmp    ax, 0         ; Is there anything left to do?
              je     writenum1     ; Jump if nothing left
              push   ax            ; Setup first (and only) parameter
              call   writenum      ; Write the number out
              add    sp, 2         ; Clean up the stack (2 bytes used)
  writenum1:  mov    dx, [bp-2]    ; Get number to display off stack
              add    dl, '0'       ; Convert binary number to ASCII
              mov    ah, 02h       ; Display character service routine
              int    21h           ; Call BDOS
              mov    sp, bp        ; Function exit sequence
              pop    bp
              ret
              .
              .
              .

 

by: Fang1964Posted on 2008-05-12 at 17:55:21ID: 21551557

;            Standardisation Example 1
       ;
       ;        This code shows how to set out standardised
       ;        assembler for the start up and the shut down
       ;        processing.

       .model   small
       .stack   1000h
       .data                      ;Start of data segment
       .code                      ;Start of code segment

       start:    mov  ax, @data   ; Get the data segment address
                 mov  ds, ax      ; Set the data segment
                 call main        ; Start program execution
       exit:     mov  ah, 4ch     ; Exit process service routine
                 int  21h         ; Call BDOS

       main:     push bp          ; Function entry sequence
                 mov  bp, sp
                 .
                 .                ; Body of main function
                 .
                 mov  sp, bp      ; Function exit sequence
                 pop  bp
                 ret
                 .
                 .                ; Rest of assembler program
                 .
                 end  start       ; Last line of code
                                  ; Start execution at star

 

by: Fang1964Posted on 2008-05-12 at 17:58:12ID: 21551564

i dont understand how to get the variables in [bp-4] etc in snippet below.

Let us first look at calling a function, with parameters, from some point in a program. There is a standard way of doing this, and the method shown below is compatible with the C programming language convention. Consider the following C code:


          .
          .
          .
          num = func(a, b);       /* call func */
          .
          .
          .

The assembly code translation of this would look something like the following:


     mov   [bp-4], ..      ; Move parameter 'a' in the stack.
     mov   [bp-6], ..      ; Move parameter 'b' in the stack.

     .
     .
     .
     mov   ax, [bp-4]   ; Setup first parameter, in local variable, a.
     push  ax           ; Push first parameter onto the stack.
     mov   ax, [bp-6]   ; Setup second parameter, in local variable, b.
     push  ax           ; Push second parameter onto the stack.
     call  _func        ; Call the function, func.
     add   sp, 4        ; On return, clean up the stack.
     mov   [bp-2], ax   ; Store value in local variable, num.
     .
     .
     .

 

by: Fang1964Posted on 2008-05-12 at 18:07:06ID: 21551586

i can see i have all the parts i have trouble with the notes. i will attach all i have to work with so you can see more clearly where i am. (i have to admit i have got to panic stations with this one it is due tomorrow night and i have full time job.)

 

by: Infinity08Posted on 2008-05-13 at 00:13:23ID: 21552860

>> sorry i got distracted by
>>
>> >>You can use the factorial code you posted earlier as a guideline

That was just a suggestion to get you started :)



>> i dont understand how to get the variables in [bp-4] etc in snippet below.

To put a value on the stack, you usually push it on the stack, like here :

     push  ax           ; Push first parameter onto the stack.

So, you put the value you want to put on the stack in ax, and then you push ax on the stack.


Take a look at the factorial code you posted earlier for example :

        push 4
        call factorial

So, 4 is pushed on the stack, and then the factorial function is called. This is equivalent to :

        factorial(4);

Inside the factorial function, you get the parameter like this :

        mov ax,[bp+8]

bp contains a copy of the stack pointer (sp). [bp+8] is the value that is 8 bytes before the top of the stack - ie. the location of the parameter. The instruction above will take that value (4 in this case), and put it in ax.

 

by: Fang1964Posted on 2008-05-13 at 00:58:51ID: 21553018

trying that again,
however when i did that and ran the debug mov ax,[bp+8] did not make ax 4 i will do it again and let you know what i get

 

by: Fang1964Posted on 2008-05-13 at 01:01:01ID: 21553025

on a side note i saw you work in telcom industry, i work for Telstra believe it or not tech/cust support for broadband services.

 

by: Infinity08Posted on 2008-05-13 at 01:07:47ID: 21553050

>> however when i did that and ran the debug mov ax,[bp+8] did not make ax 4 i will do it again and let you know what i get

What did you try ? Can you show the code ?

 

by: Infinity08Posted on 2008-05-13 at 01:08:20ID: 21553052

>> on a side note i saw you work in telcom industry, i work for Telstra believe it or not tech/cust support for broadband services.

heh :) The world is small isn't it :)

 

by: Fang1964Posted on 2008-05-13 at 01:19:22ID: 21553088

.model small ; Use the small memory model
.stack 300h  ; Include a stack segment
.data
.code
start:
    push 4
    call _exp
 
    add sp, 4
    mov ax, bx
    mov ax, 1
    ;int 0x80
    
;.type factorial, @function
_exp:
        push bp
        mov bp, sp
        
        mov ax,[bp+8]
        cmp ax, 1
        je term_cond
        
        dec ax
        push ax
        call _exp
 
	pop cx        
	mov bx, [bp+8]
        mul dword [bp+8]
	jmp short end_fact
        
term_cond:
	mov ax,1
 
end_fact:
        ;mov bp, sp
        ;pop bp
        ret
 
end start

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:

Select allOpen in new window

 

by: Fang1964Posted on 2008-05-13 at 01:22:51ID: 21553102

on the first call ax gets word 1027
if i leave out the  push bp  mov bp, sp  ax gets  0

 

by: Infinity08Posted on 2008-05-13 at 01:39:12ID: 21553161

Is this a 16bit system ?

 

by: Fang1964Posted on 2008-05-13 at 01:42:46ID: 21553174

windows xp 32bit borland turbo assembler

 

by: Infinity08Posted on 2008-05-13 at 01:44:48ID: 21553183

Because I just noticed that the standardization examples you posted are for 16bit code. Why is that ?


Can you show the contents of the stack at the moment the function is called ?

        push bp
        mov bp, sp
                                                        <---- HERE
        mov ax,[bp+8]

 

by: Fang1964Posted on 2008-05-13 at 02:18:07ID: 21553318

good question, teacher using same lecture from 10 years ago last exam he gave us to look at was 1997. thats why i sent it all to you so you can understand my confusion.

>>Can you show the contents of the stack at the moment the function is called ?

not sure have not tried

 

by: Infinity08Posted on 2008-05-13 at 02:33:47ID: 21553376

From the PDF you posted, it IS for a 16bit architecture. Are you sure you are using the correct assembler tool ? What version of borland turbo assembler are you using ?


>> not sure have not tried

Please do :)


Btw, the PDF is very informative, and explains everything with enough detail. Did you read it ?

 

by: Fang1964Posted on 2008-05-13 at 02:37:12ID: 21553399

version 4.1

i have read it many times

 

by: Infinity08Posted on 2008-05-13 at 02:46:15ID: 21553446

So, did you get the stack contents at the time of the function call ?



>> i have read it many times

Anything that wasn't clear ? Or that you have questions about ?

 

by: Fang1964Posted on 2008-05-13 at 03:04:46ID: 21553511

yes but nothing until the juction was called again from inside the function #exp#_exp

i changed function name to _exp

most of the section to do with stack and making the bits that teacher gave us work together.

 

by: Infinity08Posted on 2008-05-13 at 03:18:53ID: 21553580

>> yes but nothing until the juction was called again from inside the function #exp#_exp

Not sure what you mean.

But you said earlier that you couldn't get the parameter (the value 4) inside the function ... Is that still true ? If so, can you just show me the contents of the stack ?

 

by: Fang1964Posted on 2008-05-13 at 03:31:37ID: 21553633

sorry that was not very clear
at the point you wanted to see the stack
i went to view stack and there is nothing there.
when then function looped or called itself again the stach had  "#exp#_exp"   in it

so there is nothing at all in the view stack when in the function just before mov ax,[bp+8]

 

by: Infinity08Posted on 2008-05-13 at 03:41:25ID: 21553679

>> when then function looped or called itself again the stach had  "#exp#_exp"   in it

That looks like a stack trace (ie. function calls), not the complete contents of the stack. I don't know your debugger, but you should have the option to get a stack dump, and you should see the value 4 on there - since you pushed it on the stack.

 

by: Fang1964Posted on 2008-05-13 at 04:10:45ID: 21553792

i found it CPU has the registers to see clips
clip1 first push
clip2 the spot you wanted to see

 

by: Fang1964Posted on 2008-05-13 at 04:15:34ID: 21553823

clip2

 

by: Infinity08Posted on 2008-05-13 at 05:04:34ID: 21554140

>> clip2

So, as you see, the parameter (value 4) is at bp + 4 = 0x02FA + 4 = 0x02FE

which means that it's 16bit assembler.

In other words, use [bp + 4] instead of [bp + 8].

 

by: Fang1964Posted on 2008-05-13 at 06:01:56ID: 21554568

i had just figured that out.

 

by: Infinity08Posted on 2008-05-13 at 06:05:44ID: 21554600

Let me know if you have further questions ...

And if you finished the implementation, feel free to post it here, so I can have a look at it ...

 

by: Fang1964Posted on 2008-05-13 at 06:05:52ID: 21554603

the cpu screen is helping

 

by: Fang1964Posted on 2008-05-13 at 06:15:32ID: 21554699

need a push with this bit
mov   [bp-4], ..      ; Move parameter 'a' in the stack.
mov   [bp-6], ..      ; Move parameter 'b' in the stack.

 

by: Infinity08Posted on 2008-05-13 at 06:22:44ID: 21554762

[bp-4] and [bp-6] are used as local function variables (on the stack).

Remember that the stack grows from high to low memory addresses. So, -4 means 4 bytes UP in the stack.

Also remember that bp is the current frame pointer - it points to the start of the current stack frame.

So, [bp-4] is 4 bytes after the start of the current stack frame.

 

by: Fang1964Posted on 2008-05-13 at 07:05:04ID: 21555121

if i
mov ax , 2
mov [bp-4], ax

i cant find 2 in the stack like i could see one sent to [bp+4]

i see something happens in cs

why
please explain.

 

by: Infinity08Posted on 2008-05-13 at 07:36:25ID: 21555445

>> why
>> please explain.

As I said : -4 means that you write 4 bytes UP in the stack. If the current stack pointer is at bp, then bp-4 is ABOVE the top of the stack, so not visible when you show the stack.

              data           <--- bp + 4                             |
              data           <--- bp + 2                             |      stack grows in this direction
              data           <--- bp                                   \/
              data           <--- bp - 2
              data           <--- bp - 4

If the top of the stack is at bp for example, then the values at bp-2 and bp-4 are NOT on the stack - they are ABOVE the stack.

If you want to use the stack as local storage, you will have to increment the stack pointer by the required amount of bytes first. By using :

        add sp, 4

for example to add 4 bytes to the stack (and let sp point to bp-4)

 

by: Infinity08Posted on 2008-05-13 at 07:37:05ID: 21555453

Note that if you add bytes to the stack, you will have to take them off the stack again before the function ends !

 

by: Infinity08Posted on 2008-05-21 at 03:07:06ID: 21613435

May I ask why you gave a B grade ? That usually means that something was missing in the answer and/or that something is still unclear. If that's the case, then you can always ask for clarification, and you don't have to close the question yet.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...