简体   繁体   中英

Dynamically allocate memory in Assembly?

If I want to allocate a dynamic part of memory of an unknown size or rather size which will be known at runtime, after a user enters the number of megabytes he wants to be allocated , for example, what will the best way to do that? Is it calling "malloc" from C that is asking an OS to do so for me? Or is there a better way? How is it usually done?

Note that I don't want to reserve

The other way is to define static array as large as possible and write your own malloc / free subroutines. It is simple especially if there is no multithreading or other kind of shared usage of the allocated blocks. You keep the address of first empty block and in the beginning of each block is stored the size of block and address of next free block.

PS: allocated (reserved) blocks also contain block size as prefix. The address of next block is not used here and can be 0 as flag for "reserved" memory. More simple solution is to have only block size and flag free/used_block but in this way you have to scan multiple reserved blocks until reaching free block which is slower than a chain of only free blocks.

The mmap2 and brk system calls are the easiest way to do this in assembly. The mmap2 syscall is more difficult to use in assembly, but if you need a large amount of dynamically allocated memory, this is the way to go. brk is easy to use, it works by moving the "program break" (the boundary of your program's memory space) effectively allocating more memory for your program. This is the way to go if you need a small amount of dynamic memory (eg less than a full page).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM