So i was thinking about making my own garbage collector in C language and i've come across this tutorial that starts with the implementation of malloc function from scratch. The idea of the tutorial is to have a linked list of free blocks of memory, and whenever u use the malloc, it checks that list and gives u memory u want:
typedef struct header {
unsigned int size;
struct header *next;
} header_t;
{
size_t num_units;
header_t *p, *prevp;
num_units = (alloc_size + sizeof(header_t) - 1) / sizeof(header_t) + 1;
.....
}
The alloc_size variable, is the memory blocks we want to allocate; the num_units variable is the number of "nodes" of the lists you will have. My problem is with the formula they used , i understood the idea of (alloc_size) / sizeof(header_t) but why they added the sizeof(header_t) - 1 & the +1 .
alloc_sizeis the number of bytes that the caller is requesting. The fact that this is a number of bytes, but thatmallocallocates blocks the size of which is a multiple ofsizeof(header_t), is the reason for the formula(alloc_size + sizeof(header_t) - 1) / sizeof(header_t) + 1.(alloc_size + sizeof(header_t) - 1) / sizeof(header_t)is “just enough words to provide the requested number of bytes”.+ 1is for the room occupied by header itself. This expression is a number of words (each word being of sizesizeof(header_t)).