4

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 ?

Cloud
  • 18,753
  • 15
  • 79
  • 153
tss
  • 111
  • 1
  • 6

2 Answers2

6

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    Doubling 5 a couple of times (or infinitely, as shown in the question) indeed delivers ridicously large sizes very quickly. No matter how much you free, you will quickly reach the maximum block size allowed, forcing malloc to return real fast, too. – TheBlastOne Apr 02 '12 at 11:29
  • Thank you..this might be the reason, ll ve to check. – tss Apr 02 '12 at 11:32
2

Have you checked return values of malloc?

I think it just fails after a certain point.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121