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!
source share