Writing a malloc model in C

I am reading some malloc model code (allocateMemory). I posted a piece of code, but I could not understand the purpose of size = (size_in_bytes + sizeof (int) - 1) / sizeof (int); (Last line in published code)

void initializeHeap(void) {
    /* each chunk requires two signatures, one at the top and one
     * at the bottom, so the available space inside a chunk is 
     * the number of elements in the chunk minus 2
     */
    unsigned available_size = HEAP_SIZE - 2;

    if (initialized) { return; }


    /* write signatures at top and bottom of chunk */
    memory_pool[0] = available_size;
    memory_pool[HEAP_SIZE - 1] = available_size;
    initialized = true;
}

void* allocateMemory(unsigned size_in_bytes) {
    int size;
    unsigned chunk;
    int chunk_size;

    initializeHeap();

    size = (size_in_bytes + sizeof(int) - 1) / sizeof(int);
+3
source share
2 answers

sizeof(int). , (, SPARC) 32- , ( SIGBUS). , , x86 PPC, , . , , - - 2 , .

Malloc , , . 4, 8 16 , .

+7

sizeof(int). size int, , size_in_bytes.

+1

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


All Articles