shimon
shimon

Reputation: 86

Why does the console print "null pointer assignment" after my array is printed?

my task was to write an assembly routine that use malloc of c and insert values to it from a pointer to function in asm, the array prints what it should and everything seems right exept after the numbers that theprogram prints, it adds "NULL POINTER ASSIGNMENT"

the c file:

#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]);
} 

the asm file:

;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___________________

for every size larger than 5 its work great enter image description here

Upvotes: 2

Views: 501

Answers (1)

Van Jone
Van Jone

Reputation: 276

"null pointer assignment" message is displayed by some compilers clean up code on MSDOS platform. The clean up code checks if content of memory area around NULL ptr was changed (as there's no such thing as access violations in MSDOS). So, you need to check where your code can dereference NULL or other low offset. In the source below I can spot an error that does it:

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 returns ptr in eAX that is overwritten 2 commands later by POP eAX (containig 8). Later you dereference it by MOV [SI],eAX that is the root cause of the error message.

Upvotes: 2

Related Questions