Calloc () is 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 will work as usual. Every second a new MB is allocated in memory. The problem I am facing is that I will uncomment the calloc () line and comment out the malloc () and memset () lines. From what I know, calloc () should initialize all bytes to zero in the allocated memory; same as malloc () and memset ().

When I run the code using calloc () (without malloc () and memset ()), the initial 1 MB is allocated (as is usually the case), and then after a few seconds (~ 10) another MB is allocated.

Why is this behavior?

Thanks in advance!

+6
source share
1 answer

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

This is partly true based on my understanding of calling calloc .

It reserves space, but does not initialize all memory to zero. It often or usually initializes one partition to zero and points to all the others; when the memory is then changed or available in this block, it initializes it to zero before use. This means that calling a very large calloc does not set all this memory to zero several times, but only when it is really necessary.

tl; dr : this is an OS theory trick where kernels will cheat. Here's a more detailed description: fooobar.com/questions/8045 / ....

+9
source

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


All Articles