Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calloc() slower than malloc() & memset()

I would like to ask you a question. I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define XXX 1024*1024

int main()
{
        int *p;
        unsigned long x=0;
        while (1)
        {
                //p = (int *) calloc (1,XXX);
                p = (int *) malloc (XXX);
                memset (p,0,XXX);
                x++;
                printf ("%lu MB allocated.\n",x);
                sleep (1);
        }
        return 0;
}

If I run this code, everything runs as normal. Every second, a new MB is allocated in the memory. The problem I encounter is if I uncomment the calloc() line and comment the malloc() and memset() lines. From what I know, calloc() should initialize all bytes to zero in the allocated memory; the same thing that malloc() and memset() do.

When I run the code with calloc() (without the malloc() and memset()), an initial 1 MB is allocated (as it is normal), and then after some seconds (~10) another MB is allocated.

Why is this behaviour?

Thanks in advance!

like image 231
Alex Avatar asked Nov 06 '13 13:11

Alex


1 Answers

From what I know, calloc() should initialize all bytes to zero in the allocated memory.

This is partly true based on my understanding of the calloc call.

It reserves the space but doesn't initialise all memory to zero. It will often or generally initialise one section to zero, and point all others to that; when memory is then modified or accessed within this block, it will initialise it to zero before using. It means that a calloc call of very large size doesn't set all of that memory to zero multiple times, but only when it actually needs to.

tl;dr: it's an OS theory trick where kernels will cheat. There's a longer description here: https://stackoverflow.com/a/2688522/2441252.

like image 154
Leigh Avatar answered Sep 23 '22 19:09

Leigh