I ve a code which increases the size of the memory(identified by a pointer) exponentially.
Instead of realloc()
, I use malloc()
followed by memcpy()
...
int size=5,newsize;
int *c = malloc(size*sizeof(int));
int *temp;
while(1)
{
newsize=2*size;
//begin time
temp=malloc(newsize*sizeof(int));
memcpy(temp,c,size*sizeof(int));
//end time
//print time in mili seconds
c=temp;
size=newsize;
}
Thus the number of bytes getting copied is increasing exponentially.
The time required for this task also increases almost linearly with the increase in size. However after certain point, the time taken abruptly reduces to a very small value and then remains constant.
I recorded time for similar code, copying data of my own type.
5 -> 10 - 2 ms
10 -> 20 - 2 ms
.
.
2560 -> 5120 - 5 ms
.
.
20480 -> 40960 - 30 ms
40960 -> 91920 - 58 ms
367680 -> 735360 - 2 ms
735360 -> 1470720 - 2 ms
1470720 -> 2941440 - 2 ms
What is the reason for this drop in time ? Does a more optimal memcpy method get called when the size is large ?
Since your code doesn't do free()
on the old memory block, make sure that the new allocations simply don't start to fail. It could be that memcpy()
errors out when given a NULL pointer, thus completing very quickly.
Have you checked return values of malloc
?
I think it just fails after a certain point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With