Saturday, January 26, 2019

c - Difference in block allocated by malloc/calloc











Though calloc allocates memory in the form of blocks and malloc in a single block , do they both allocate memory continuously and if there is an obstacle , would calloc be able to jump the obstacle then allocate another block in remaining heap memory. I would like clarity in the matter.


Answer



Both functions allocate memory in one contiguous block. The difference in parameters does not reflect a difference in the underlying allocation strategy. It's a historical inconsistency, nothing more.



(You can reason your way to this conclusion. If calloc were to allocate non-contiguous blocks, how would the caller know where the holes are and how to skip over them? All the caller receives is a single pointer. Not, say, a linked list of blocks, which is what would be required to access non-contiguous regions.)




You either call calloc(n,s) or malloc(n*s); calloc does the multiplication for you, that's all. You could switch the arguments to calloc(s,n) if you wanted. The idea that it allocates "s" objects of size "n" is just a conceptual one, the system doesn't actually keep track of that or enforce it. calloc(4,1) is equivalent to calloc(1,4) is equivalent to calloc(2,2).



The only meaningful distinction between the two is that calloc sets the memory to zero. malloc leaves it uninitialized, so it is more efficient if you don't need the memory cleared.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...