打印数组后,为什么控制台会打印“空指针赋值”?

时间:2012-12-25 17:13:16

标签: c assembly malloc

我的任务是编写一个程序集例程,它使用c的malloc并从指向asm中的函数的指针插入值,数组打印它应该是什么,并且在程序打印的数字之后一切似乎正确,它添加“ NULL POINTER ASSIGNMENT“

c文件:

#include <stdio.h>
#include <stdlib.h>

extern  int initarr (int** arr, int n, int (*initfunc)());

int getNum() 
{return (rand()%1000);}

void main()
{
int * arr, i, n, success;
printf("\nPlease enter the array size\n");
scanf("%d",&n);
success = initarr(&arr, n, getNum);   
if(!success) 
{
    printf("Memory Allocation Failed\n");
    return;
} 
printf("\nThe Numbers in the allocated array are:\n");
for(i=0; i<n; i++)   
    printf("%d  ", arr[i]);
} 

asm文件:

;lab10.asm
.MODEL SMALL
.CODE
.386
;extern  int initarr (int** arr, int n, int (*initfunc)())
;arr=BP+4   n=BP+6  function=BP+8
EXTRN _malloc : NEAR
PUBLIC _initarr
_initarr PROC NEAR 
PUSH BP;preserve BP
MOV BP,SP;let me see whats in the stack
PUSH SI;preserve SI
MOV SI,[BP+4];SI controls array
MOV CX,[BP+6];CX=n from declaration
MOV eAX,8;size of one byte=8
MUL CX;how many bytes to allocate
SUB eSP,eAX;size in bytes to allocate
PUSH eAX;preserve for later add to sp
PUSH eCX;for ussing malloc
CALL _malloc;return addres is in eAX
TEST eAX,eAX;checks if allocation succeded
POP eCX;pop CX for the loop
POP eAX;pop AX to add to SP
ADD eSP,eAX;for stack won't change
JZ BYE;if allocation went wrong and eAX is already 0
MOV [SI],eAX;sets SI to point at the array
MOV SI,[SI];set SI to the array
LOOPER:
PUSH CX;for ussing rand
CALL [BP+8];call function
POP CX;pop CX for the loop
MOV [SI],eAX
ADD SI,2
LOOP LOOPER
;end of loop    
MOV eAX,1;for the return value
BYE:
POP SI;restore SI
POP BP;restore BP
RET
_initarr ENDP
END 

enter image description here

__________________ EDIT ___________________

对于每个大于5的尺寸,它的工作都很棒 enter image description here

1 个答案:

答案 0 :(得分:2)

“空指针赋值”消息由某些编译器显示在MSDOS平台上清理代码。清理代码检查NULL ptr周围的内存区域内容是否已更改(因为MSDOS中没有访问冲突)。因此,您需要检查代码可以取消引用NULL或其他低偏移量的位置。在下面的源代码中,我可以发现一个错误:

CALL _malloc;return addres is in eAX
TEST eAX,eAX;checks if allocation succeded
POP eCX;pop CX for the loop
POP eAX;pop AX to add to SP
ADD eSP,eAX;for stack won't change

_malloc在eAX中返回ptr,稍后由POP eAX(包含8)覆盖2个命令。稍后您将MOV [SI],eAX取消引用它,这是错误消息的根本原因。