Home >> Assembly Programming


Memory in DOS

I am not expert on this subject, but this is my current understanding of the issue; when a program is started and loaded into memory in DOS, it is given all available memory. If the program wants to dynamically allocate memory on-the-fly, it has to re-allocate the memory-block DOS has given it. So, the program must find out how much memory it needs, then re-allocate the memory-block to the size it needs, and then it is possible to allocate the now  free memory dynamically.

When a program is loaded, ES and DS points to the Program Segment Prefix - PSP.

Allocating memory

;---------------------------------------------------------------	
%TITLE "dosmem.asm"
;---------------------------------------------------------------

IDEAL
DOSSEG
MODEL small
STACK 256

;---------------------------------------------------------------
DATASEG
;---------------------------------------------------------------

excode DB 0h

;---------------------------------------------------------------
UDATASEG
;---------------------------------------------------------------

mem_seg DW ?

;---------------------------------------------------------------
CODESEG
;---------------------------------------------------------------

start:

;----> re-allocate memory

mov cx, sp ; size of stack
shr cx, 4 ; convert to paragraphs
inc cx
add ax, cx ; prog size + stack size

mov bx, ax ; new size of allocated memory
mov ah, 4Ah ; es still points to
int 21h ; start of program (psp)

jc @@error ; error? Then jump


;----> allocate memory

mov ah, 48h
mov bx, MEMSIZE ; num of paragraphs to allocate
int 21h

jc @@error ; error? Then jump

mov [mem_seg], ax ; save pointer to allocted mem

;---------------------------------------------------------------

< Code here >



;---------------------------------------------------------------

@@error:
;----> write error code

mov dx, ax ; 7, 8 or 9 in ax on error
mov ah, 02h
add dl, 30h
int 21h ; print to screen and exit
;---------------------------------------------------------------

exit:
mov ah, 04Ch ; DOS function: Exit program
mov al, [excode] ; Return exit code value
int 21h ; Call DOS. Terminate program

;---------------------------------------------------------------

END start ; End of program / entry point


Home >> Assembly Programming