calloc v/s malloc and time efficiency
Posted
by yCalleecharan
on Stack Overflow
See other posts from Stack Overflow
or by yCalleecharan
Published on 2010-04-09T06:26:37Z
Indexed on
2010/04/09
6:33 UTC
Read the original article
Hit count: 405
Hi, I've read with interest the post "c difference between malloc and calloc". I'm using malloc in my code and would like to know what difference I'll have using calloc instead.
My present (pseudo)code with malloc:
Scenario 1
int main()
{
allocate large arrays with malloc
INITIALIZE ALL ARRAY ELEMENTS TO ZERO
for loop //say 1000 times
do something and write results to arrays
end for loop
FREE ARRAYS with free command
} //end main
If I use calloc instead of malloc, then I'll have:
Scenario2
int main()
{
for loop //say 1000 times
ALLOCATION OF ARRAYS WITH CALLOC
do something and write results to arrays
FREE ARRAYS with free command
end for loop
} //end main
I have three questions:
Which of the scenarios is more efficient if the arrays are very large?
Which of the scenarios will be more time efficient if the arrays are very large?
In both scenarios,I'm just writing to arrays in the sense that for any given iteration in the for loop, I'm writing each array sequentially from the first element to the last element. The important question: If I'm using malloc as in scenario 1, then is it necessary that I initialize the elements to zero? Say with malloc I have array z = [garbage1, garbage2, garbage 3]. For each iteration, I'm writing elements sequentially i.e. in the first iteration I get z =[some_result, garbage2, garbage3], in the second iteration I get in the first iteration I get z =[some_result, another_result, garbage3] and so on, then do I need specifically to initialize my arrays after malloc?
© Stack Overflow or respective owner