Saturday, March 20, 2010

Difference between malloc and calloc

One of the most basic things a person familiar with programming language 'C' is supposed to know is:
What is the difference between the malloc and the calloc function calls?
Query Google and it'll tell you how many folks are interested in the answer to this question. The reason for that is that it is one of the most commonly asked questions in job interviews at the beginner's level.

Since the readers here may not possess that familiarity, the answer that's usually expected is:
While both the functions allocate memory, calloc() additionally initializes all the locations in the newly allocated memory block to '0'.
That's that. That answer is sufficient for the interview. That's all I knew. Until now.

I was reading The Old New Thing today and there was a mention of Copy-on-Write (CoW) in one of the posts. To understand it better, I decided to read about CoW on Wikipedia. From the Wikipedia page, I found out that calloc can be implemented using CoW:
Another use is in the calloc function. This can be implemented by having a page of physical memory filled with zeroes. When the memory is allocated, the pages returned all refer to the page of zeroes and are all marked as copy-on-write. This way, the amount of physical memory allocated for the process does not increase until data is written.
Nice, I said to myself. Note taken. Thanks TONT, Wikipedia!
blog comments powered by Disqus