thlgood
thlgood

Reputation: 1295

Write a function allocate dynamically memory like malloc

How can I implement malloc on a Linux platform?

Upvotes: 1

Views: 454

Answers (2)

rach5000
rach5000

Reputation: 135

The sbrk() function is probably what you are looking for. It increases the size of the heap by the number of bytes you specify.

Once you have been given this new chunk of memory it is up to you to choose how you want to manage your allocated and free bytes. I personally think the binary buddy system is a good algorithm to start with - googling that will give you some solid explanations. There are also the first fit, last fit, best fit, and worst fit algorithms, among others. Of course, as with anything else each has its advantages and disadvantages.

As far as a simple implementation of malloc()/free() goes, K&R C has a good one.

Upvotes: 3

ugoren
ugoren

Reputation: 16441

In Linux, malloc is based on two functions:

  1. brk - changes the size of the heap. Once you've increased the size, it's up to you to manage the heap. NOTE: If you manage the heap, the normal malloc must not do it. So this way requires disabling all calls to malloc (including implicit ones, like strdup).

  2. mmap - allocates one or more pages from the kernel (can also used be for file I/O). When you have memory pages, you can manage them somehow and return smaller pieces to the callers. You can do this in parallel to malloc - it will manage pages it gets, you'll manage pages you get.

Upvotes: 6

Related Questions