2017-04-14 102 views
1

我想运行由我的教授编写的代码。不幸的是,当我编译和运行代码,结果:x86汇编堆内存分配

INCLUDE Irvine32.inc 
.data 
ARRAY_SIZE = 1000 
FILL_VAL EQU 0FFh 

hHeap HANDLE ?      ;Handle to the process heap 
pArray DWORD ?       ;pointer to block of memory 
newHeap DWORD ?       ;handle to new heap 
str1 BYTE "Heap size is: ",0 

GetProcessHeap PROTO 

.code 
main PROC 

    INVOKE GetProcessHeap     ;get handle prog's heap 
    .IF eax = NULL       ;If failed, display message 
    call WriteWindowsMsg 
    jmp quit 
    .ELSE 
    mov hHeap, eax       ;success 
    .ENDIF 

    call allocate_array 
    jnc arrayOk        ;failed (CF = 1)? 
    call WriteWindowsMsg 
    call Crlf 
    jmp quit 

arrayOk: 
    call fill_array 
    call display_array 
    call Crlf 

    ;free the array 
    INVOKE HeapFree, hHeap, 0, pArray 

quit: 
    exit 
main ENDP 

;------------------------------------------------------- 
allocate_array PROC USES eax 
; 
;Dynamically allocates space for the array 
;Receives: EAX = handle to the program heap 
;Returns: CF = 0 if the memory allocation succeeds 
;------------------------------------------------------- 
INVOKE HeapAlloc, hHeap, HEAP_ZERO_MEMORY, ARRAY_SIZE 

    .IF eax == NULL 
     stc       ;return with CF = 1 
    .ELSE 
     mov pArray, eax    ;save the pointer 
     clc       ;return with CF = 0 
    .ENDIF 

    ret 
allocate_array ENDP 

;-------------------------------------------------------- 
fill_array PROC USES ecx edx esi 
; 
;Fills all array positions with a single character 
;Receives: nothing 
;Returns: nothing 
;--------------------------------------------------------- 

    mov ecx, ARRAY_SIZE    ;loop counter 
    mov esi, pArray     ;point to the array 

L1: mov BYTE PTR [esi], FILL_VAL ;fill each byte 
    inc esi       ;next location 
    loop L1 

    ret 
fill_array ENDP 
;--------------------------------------------------------- 
display_array PROC USES eax ebx ecx esi 

; Displays the array 
; Receives: nothing 
; Returns: nothing 

mov ecx, ARRAY_SIZE  ;loop counter 
mov esi, pArray   ;point to the array 

L1: mov al, [esi]  ;get a byte 
    mov ebx, TYPE BYTE 
    call WriteHexB  ;display it 
    inc esi    ;next location 
    loop L1 

    ret 
display_array ENDP 

END main 

以下结果:

bobnew.asm(41) : error A2006: undefined symbol : HeapFree 
bobnew.asm(56) : error A2006: undefined symbol : HeapAlloc 
bobnew.asm(22) : error A2006: undefined symbol : WriteWindowsMsg 
bobnew.asm(30) : error A2006: undefined symbol : WriteWindowsMsg 
bobnew.asm(97) : error A2006: undefined symbol : WriteHexB 

有人能解释这是为什么。谢谢。我也很好奇堆内存分配以及Invoke和处理程序和Proto如何协同工作。我知道堆是用于动态内存分配的内存,与堆栈不同,没有设置内存如何分配或释放的模式。您可以随时随机分配和释放分配内存,随时释放分配的内存。另外,与堆栈不同,必须手动销毁堆内存以防止内存。

回答

2

你是如何构建可执行文件的?

为了使用像HeapFree这样的功能,您需要链接kernel32。如何做到这一点可以根据您使用的链接器而有所不同。在MASM中这可能意味着写作

include  \masm32\include\kernel32.inc 
includelib \masm32\lib\kernel32.lib 
+0

不幸的是,我尝试了这个建议,它没有奏效。谢谢。 –