2017-07-04 35 views
-2

我正在做C和程序集,我想我會寫一個簡單的代碼,以確保我瞭解如何在程序集中使用malloc,我只想分配一個大小爲4的int數組並填充1,2,在裝配和隨後3,4-值打印C.程序集8086中的malloc如何工作?

C文件:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <malloc.h> 
extern void myproc(int *arr); 
void main() { 
int *p; 
myproc(p);//call the assembly function ,where i do p=malloc(sizeof(int)*4) 
printf("%d %d %d %d ",p[0],p[1],p[2],p[3]);//supposed to print 1 2 3 4 but its not 
} // main 

大會文件:

.MODEL small 
    .STACK 100H 
    .DATA 
    .CODE 
    .386 
    .387 
    PUBLIC _myproc 
    EXTRN _malloc:NEAR 
    _myproc PROC NEAR 
    ;This procedure is supposed to do p=malloc(sizeof(int)*4) then p[0]=1 ,p[1]=2,p[2]=3,p[3]=4. 
    PUSH BP 
    MOV BP,SP 
    XOR DX,DX 
    PUSH BX 
    MOV AX,4;prepare to pass the parameter for malloc 
    SHL AX,1;multiply by 2 for int array 
    PUSH AX;pass 4*2 to malloc 
    CALL _malloc;calling malloc 
    ADD SP,2 
    MOV WORD PTR [BP+4],AX;set the pointer to the newly allocated array 
    MOV BX,WORD PTR [BP+4] 
    ;do p[0]=1 ,p[1]=2,p[2]=3,p[3]=4 
    MOV WORD PTR [BX],1 
    ADD BX,2 
    MOV WORD PTR [BX],2 
    ADD BX,2 
    MOV WORD PTR [BX],3 
    ADD BX,2 
    MOV WORD PTR [BX], 4 
    POP BX 
    POP BP 
    RET;;when i get back to the C file to print the values it doesnt work ,its like i didn't set 1,2,3,4. 
    _myproc ENDP 

    END 
+1

你可以發佈一個線程之前總是搜索.. https://stackoverflow.com/questions/20510132/what-exactly-does-malloc- do-in-assembly – SpaceX

+2

[\ _malloc在彙編中做了些什麼?](https://stackoverflow.com/questions/20510132/what-exactly-does-malloc-do-in-assembly) –

+4

可能的重複請注意, 'myproc(p);'不能改變'p'的值,因爲C是按值傳遞的。你需要'p = myproc();''或'myproc(&p);'。 – unwind

回答

1

功能更改爲extern void myproc(int **arr);然後傳遞&p。 和不斷變化的大會這樣的:

.MODEL small 
    .STACK 100H 
    .DATA 
    .CODE 
    .386 
    .387 
    PUBLIC _myproc 
    EXTRN _malloc:NEAR 
    _myproc PROC NEAR 
    ;This procedure is supposed to do p=malloc(sizeof(int)*4) then p[0]=1 ,p[1]=2,p[2]=3,p[3]=4. 
    PUSH BP 
    MOV BP,SP 
    XOR DX,DX 
    PUSH BX 
    PUSH SI 
    MOV AX,4;prepare to pass the parameter for malloc 
    SHL AX,1;multiply by 2 for int array 
    PUSH AX;pass 4*2 to malloc 
    CALL _malloc;calling malloc 
    ADD SP,2 
    MOV SI,WORD PTR [BP+4];get the pointer adress 
    MOV [SI],AX;set the point to point on the newly allocated array 
    ;do p[0]=1 ,p[1]=2,p[2]=3,p[3]=4 
    MOV BX,[SI] 
    MOV WORD PTR [BX],1 
    ADD BX,2 
    MOV WORD PTR [BX],2 
    ADD BX,2 
    MOV WORD PTR [BX],3 
    ADD BX,2 
    MOV WORD PTR [BX], 4 
    POP SI 
    POP BX 
    POP BP 
    RET;;when i get back to the C file to print the values it doesnt work ,its like i didn't set 1,2,3,4. 
    _myproc ENDP 

    END 

修復它