Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory and pointers

I have need some some help with some thinking around a task.

My task is to create one memory area

void *memory = malloc(320);

and then use pointers to store texts into this storage place: We want to divide this area into data blocks of 32 bytes, sow we can store: 320/32 = 10 data blocks a 32 bytes. Into one data block I can store (1 ASCSII char = 1 bytes) 32 characters.

I have a bitmap that is 10 long where every bit indicates if data block is used(1) or not(0).

But what if I want to store a text that is 60 characters long? Then i need 2 data blocks (2 x 32 bytes). The bitmap shows that data block 2 and 6 are free, 1 and 6 is not side by side. How can I achieve this?

struct  data {
    char * text;
};

typedef struct data d;

d->text = ???
like image 352
user265767 Avatar asked Oct 13 '22 22:10

user265767


1 Answers

This is called memory fragmentation and is a serious problem. You have to report out of memory even though there is technically enough to support the block.

Managed languages like C# that don't allow pointers (in the normal case - please don't fixate on this) have the freedom to rearrange the underlying memory and fix this problem (though it's not free in terms of performance).

To fix the problem in C:
There's not a lot you can do because those pointers into the memory prevent you from reshuffling everything. Someone else has mentioned the buddy system and there are others but few are simple. A lot are based on having preset 'big chunks' and 'small chunks' and only allowing small requests small chunks etc... but that's all to stop arriving at the problem in the first place, once you're there you either deny the memory request or expand the pool.

like image 51
Daniel Avatar answered Oct 18 '22 12:10

Daniel