C memory allocator - how to use sbrk () 'ed space

I am writing a malloc implementation and was wondering if anyone could help me with this problem.

Basically, I would like to reuse the memory after allocating it with sbrk () and making sure that the memory is free.

So imagine my memory is like this

|------------------------------| 

... and I make some highlight. When I allocate memory, each bit has a head (h) and data (d).

 |hddddddhddd---hdd--hddd-------| 

Now I have these holes, and if I want to use the first space in my diagram, how can I configure it so that it gets the head (h) and the body (dd) as well?

I got to the point that now I have a pointer to the memory cell that I want. In C, its pointer points to a pointer. The pointer has a custom type, where "meta" is the structure I defined. So now I have

 metaStruct * mypointer = the memory address. 

But when I try to do

 mypointer->size = 30; 

or

 mypointer->buddy = 1; 

I get segfault.

Question: how to configure it so that the memory address that was allocated via sbrk () will have the form of my structure? Obviously, I cannot just go myPointer = malloc (sizeof (metaStruct)), because I write malloc itself. I'm also not interested in sbrk (), taking up more space, but instead use the existing space that I point to (I want to ignore its unnecessary data and use a space).

How can I do it?

+4
source share
1 answer

As far as I know, p = sbrk (n) extends the available address space (at least) n bytes and returns the base address of the new selection in "p". So now you have a block of memory starting with "p" and n bytes (maybe more than n, it depends on the system).

So, I suppose your “metaStruct” contains the “size” field, the “next free area” field and the “data” field,

 metaStruct * m ; p=sbrk(sizeof(metaStruct)+ data_size); m = (metaStruct *)p; m->size = data_size; m->next = NULL; memcpy(m->data, ...,data_size); 

The code is not perfect, on some systems the sbrk function (indeed, it is often a function, and not a basic system call - and, of course, you must check if sbrk works) does not return aligned pointers, so you need to align the pointer manually. Alternatively, you can get the actual allocated size by calling sbrk (0) after sbrk (n) and calculating the difference between the two pointers. In general, you should create a collection of "free blocks" and try to use them with your fist, and then call sbrk only if none of them are big enough.

+4
source

Source: https://habr.com/ru/post/1345323/


All Articles