Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a model of malloc in C

Tags:

c

I'm reading some code of a model malloc (allocateMemory). I have posted a portion of the code, but I couldn't understand the purpose of size = (size_in_bytes + sizeof(int) - 1) / sizeof(int); (The last line in the posted 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);
like image 288
user133466 Avatar asked Dec 19 '25 08:12

user133466


1 Answers

It rounds the size up to a multiple of sizeof(int). This is normally done for alignment purposes since on some machines (for instance SPARC) you cannot access a 32-bit wide value that is aligned on an odd address (typical symptom is a SIGBUS). And even on processors that do support unaligned access, like x86 and PPC, it's often slower than an aligned access. It's also useful to help prevent cache splits, where half of the data is in one cache line and half is in another - this slows down access to the value by a factor of 2, which is pretty nasty.

Malloc has to assume the largest possible useful alignment because it does not know the size of the things it is allocating. Typically that is 4, 8, or 16 bytes, depending on the machine.

like image 181
Jack Lloyd Avatar answered Dec 21 '25 20:12

Jack Lloyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!