目录

汇编 - 内存管理(Memory Management)

sys_brk()系统调用由内核提供,用于分配内存而无需在以后移动它。 此调用在内存中的应用程序映像后面分配内存。 此系统功能允许您在数据部分中设置最高可用地址。

此系统调用采用一个参数,这是需要设置的最高内存地址。 该值存储在EBX寄存器中。

如果有任何错误,sys_brk()返回-1或返回负错误代码本身。 以下示例演示了动态内存分配。

例子 (Example)

以下程序使用sys_brk()系统调用分配16kb的内存 -

section	.text
   global _start         ;must be declared for using gcc
_start:	                 ;tell linker entry point
   mov	eax, 45		 ;sys_brk
   xor	ebx, ebx
   int	80h
   add	eax, 16384	 ;number of bytes to be reserved
   mov	ebx, eax
   mov	eax, 45		 ;sys_brk
   int	80h
   cmp	eax, 0
   jl	exit	;exit, if error 
   mov	edi, eax	 ;EDI = highest available address
   sub	edi, 4		 ;pointing to the last DWORD  
   mov	ecx, 4096	 ;number of DWORDs allocated
   xor	eax, eax	 ;clear eax
   std			 ;backward
   rep	stosd            ;repete for entire allocated area
   cld			 ;put DF flag to normal state
   mov	eax, 4
   mov	ebx, 1
   mov	ecx, msg
   mov	edx, len
   int	80h		 ;print a message
exit:
   mov	eax, 1
   xor	ebx, ebx
   int	80h
section	.data
msg    	db	"Allocated 16 kb of memory!", 10
len     equ	$ - msg

编译并执行上述代码时,会产生以下结果 -

Allocated 16 kb of memory!
↑回到顶部↑
WIKI教程 @2018