1

我在这里询问了如何在 MASM 中动态分配内存,但我还有 2 个问题。

如何为字节分配内存?

.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>

第二个问题,我可以在多线程应用程序中使用这种分配内存的方法还是应该使用 GlobalAlloc?

4

1 回答 1

1

HeapAlloc函数接受 3 个参数:

hHeap- 堆对象的句柄

flags- 标志,关于如何分配内存

size- 你需要的内存块大小

该函数返回一个双字,EAX它是一个指向已分配内存的指针。

您不需要GetProcessHeap在每次调用 HeapAlloc 时都调用它。

变量tabresult必须是双字,因为指针是双字长(eax)

这些指针指向的内存块可以以您需要的任何数据大小进行访问。它们只是内存块。

Windows 堆函数是线程安全的,您可以在多线程应用程序中使用它们。

这一切在装配中的样子:

    .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
于 2015-01-14T17:41:28.713 回答