MASM dll memory allocation in multithreading application

372 views Asked by At

I asked how to dynamically allocate memory in MASM here but I got 2 more questions.

How can I allocate memory for bytes?

.data
tab DB ?
result DB ?

.code
invoke GetProcessHeap
; error here
mov tab, eax          ; I cannot do this because of wrong sizes, AL and AH are equal 0
INVOKE HeapAlloc, tab, 0,  <size>

invoke GetProcessHeap
mov result, eax          ; same here
INVOKE HeapAlloc, result, 0,  <size>

Second question, can I use this method of allocating memory in multithreading application or should I use GlobalAlloc?

1

There are 1 answers

11
johnfound On BEST ANSWER

HeapAlloc function accepts 3 arguments:

hHeap - handle of a heap object

flags - flags, about how the memory should be allocated

size - The size of the memory block you need

The function returns one double word in EAX that is a pointer to the allocated memory.

You don't need to call GetProcessHeap on every call to HeapAlloc.

The variables tab and result must be double word, because the pointers are double word long (eax)

The memory blocks pointed by these pointers can be accessed in whatever data size you need. They are simply blocks of memory.

Windows heap functions are thread safe and you can use them in multi-thread applications.

How this all will look in assembly:

    .data

tab    dd ?
result dd ?

    .code

    invoke GetProcessHeap
    mov    ebx, eax          ; the heap handle

    invoke HeapAlloc, ebx, 0, <size>
    mov    tab, eax     ; now tab contains the pointer to the first memory block     

    invoke HeapAlloc, ebx, 0,  <size>
    mov    result, eax          ; now result contains the pointer to the second block