OSDev.org
https://forum.osdev.org/

How do I allocate memory correctly?
https://forum.osdev.org/viewtopic.php?f=15&t=36732
Page 1 of 1

Author:  mrjbom [ Thu Apr 30, 2020 7:49 pm ]
Post subject:  How do I allocate memory correctly?

Hi.
I already have a ready-made memory Manager that divides memory into 4 KB pages and allocates it on request.
If I call kmalloc (10), it will allocate one page of 4096 bytes, and if kmalloc(5000), it will allocate 2 pages of 4096 bytes.
I was wondering if it is correct to allocate as many as 4096 bytes to a query, for example, 10 bytes. On the one hand, this makes memory managers work faster, but on the other hand, a lot of memory is wasted.
Is this approach correct? Maybe you should change something?
Thanks.

Author:  BenLunt [ Thu Apr 30, 2020 9:01 pm ]
Post subject:  Re: How do I allocate memory correctly?

There are a lot of different types of memory allocation. One suggestion I would make is that you divide your page allocation (allocating 4096 byte pages) and your actual memory allocation so that they are separate. For example, the physical memory allocation should be completely different that the virtual allocation, even if the virtual allocation are still physical addresses. i.e.: If you don't have paging enabled, you still need to have these separated.

My system has a heap of memory physically allocated for the kernel, then has a memory allocation unit that allocates different sized memory blocks within that heap. The one has no idea about the other. If the heap becomes full, it simply calls the other to allocation more heap.

If you are looking for speed, write your allocation so that the block that was just unallocated will be the next block allocated. This keeps the memory in the cache lines.

If you are looking for size of allocation optimization, create a linked list of some sort. The main idea is to get away from the 4k idea, since the "virtual" allocation should have no idea of the size of the physical page allocation. This allows you to allocate small blocks or big blocks and not waste any memory.

Again, there are many ways to allocation memory, some having great advantages over others, while those others have advantages over the first.

Ben

Page 1 of 1 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/