我正在做C和汇编,我想我会编写一个简单的代码来确保我理解如何在汇编中使用malloc,我只想分配一个4号int数组并用1,2填充它,汇编中的3,4值,然后用C打印。
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
答案 0 :(得分: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
修复它