Dynamic memory allocation under Linux

Even in not-so-advanced programs there may be a need to allocate some memory dynamically, during the program running, without knowing in advance how much memory will be needed. For example, the user gives a size of an array and our program has to create such an array and operate on it (without knowing in advance even the maximum size). Dynamic memory allocation is the solution to such problems. To allocate memory under Linux, use the sys_brk system function (setting the highest available address in the data section). It takes one parameter:

If something went wrong, sys_brk will return -1 (and set the errno variable accordingly) or return the negative error code itself. the function parameter can of course be greater (allocation) or lower (memory freeing) than the value returned by sys_brk with EBX=0.

As you can see, the theory isn't complicated. Let's move to the example then. This short program will allocate 16kB of memory (this much on purpose, to exceed 4kB - size of one page - and prove that the memory was really allocated) and zero it out (normally, writing to unassigned memory will result in our program being closed by the system).


(skip the code)
; Dynamic memory allocation under Linux
;
; Author: Bogdan D., bogdandr (at) op.pl
;
; assembly:
;
; nasm -f elf -o alok_linux.o alok_linux.asm
; ld  -o alok_linux alok_linux.o


section	.text
global	_start

_start:

	mov	eax, 45		; sys_brk
	xor	ebx, ebx
	int	80h

	add	eax, 16384	; this much to reserve
	mov	ebx, eax
	mov	eax, 45		; sys_brk
	int	80h

	cmp	eax, 0
	jl	.problem	; if error, exit the program. Nothing will
				; be displayed

	mov	edi, eax	; EDI = highest available address

	sub	edi, 4		; EDI points to the last DWORD available to us
	mov	ecx, 4096	; this many DWORDs were allocated
	xor	eax, eax	; will write with zeroes
	std			; walk backwards
	rep	stosd		; write all over the reserved area
	cld			; bring back the DF flag to normal state

	mov	eax, 4
	mov	ebx, 1
	mov	ecx, info
	mov	edx, info_dl
	int	80h		; print a message

.problem:

	mov	eax, 1
	xor	ebx, ebx
	int	80h



section	.data

info		db	"Memory allocation succeeded.", 10
info_dl		equ	$ - info


On-line contents (Alt+2)
Helpers for people with disabilities (Alt+0)