The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: James Ladd on May 08, 2005, 04:27:56 AM

Title: Allocating the right amount of memory ...
Post by: James Ladd on May 08, 2005, 04:27:56 AM
I need to allocate 'n' times a structure in memory.
Like 'n' * sizeof MYSTRUCT

Im ok on how to do the allocation, but not on the multiplication to arrive at the correct
allocation size. ie: I cant just do a    mov eax, var * sizeof MYSTRUCT

So how do I do this ?

rgs, striker
Title: Re: Allocating the right amount of memory ...
Post by: hutch-- on May 08, 2005, 05:23:59 AM
A couple of questions, how many times must you do the calculation . If its within loop code I would be looking for a fast way to do it and this will depend if its a constant multiplication factor or not. Shifts, LEA and ADD are the type of instructions that come to mind if its a constant, if not, you can use the integer capacity of FP code to do a simple MUL or code a normal integer mul with MUL or IMUL.
Title: Re: Allocating the right amount of memory ...
Post by: James Ladd on May 08, 2005, 05:25:28 AM
I do it once, and currently I do this....


    mov eax, sizeof STRUCT
    mov ecx, count_of_items_i_want
    mul ecx
    ; go on and allocate 'eax' bytes


Do this appear correct ?

rgs, striker
Title: Re: Allocating the right amount of memory ...
Post by: hutch-- on May 08, 2005, 05:32:27 AM
I doubt that you will improve on that for a variable size mul.
Title: Re: Allocating the right amount of memory ...
Post by: thomasantony on May 08, 2005, 08:46:53 AM
Hi,
   If the size of your array is a power of 2 (like 2, 4,8,16,32 etc). You can use shifts instead. SHL for multiply, SHR for divide. For example for multiplying eax by 8 do

shl eax,3  ; 8 = 2^3

and for multiplying by 32

shl eax,5  ; 32 = 2^5


Thomas :U
Title: Re: Allocating the right amount of memory ...
Post by: Mark Jones on May 08, 2005, 02:48:02 PM
Hutch, could it be any faster if the math were "offloaded" to the ALU? Maybe this is a question for Michael. :)
Title: Re: Allocating the right amount of memory ...
Post by: raymond on May 08, 2005, 05:00:24 PM
Quote from: striker on May 08, 2005, 05:25:28 AM
I do it once, and currently I do this....


    mov eax, sizeof STRUCT
    mov ecx, count_of_items_i_want
    mul ecx
    ; go on and allocate 'eax' bytes


Do this appear correct ?


rgs, striker


You can save yourself one line of code with:
    mov eax, sizeof STRUCT
    mul  count_of_items_i_want


AND, being done only once in your app, you would be wasting a zillion times more time trying to optimize those two lines compared to the fractional nanosecond you could save. ::) ::) ::) ::)

Raymond
Title: Re: Allocating the right amount of memory ...
Post by: James Ladd on May 08, 2005, 09:12:37 PM
Thanks for the replies.
I just wanted to know how to do it, not the fastest way.

Raymond - thanks for saving me 1 line. Ill use your approach.