3 ms·
> no, it won't move your memory around into larger areas every time you call it. Most of the time it will simply bump up the allocation end point. This happens
by abainbridge 3y ago
> no, it won't move your memory around into larger areas every time you call it. Most of the time it will simply bump up the allocation end point. This happens more frequently than you think.
I just tried some simple "I want to grow my block of memory" test cases. A malloc of 1000 bytes couldn't be increased by a single byte without being moved to a new location. An allocation of 1 million bytes couldn't be increased by 1% without being moved to a new location.
https://godbolt.org/z/Gr4bchxv5 https://godbolt.org/z/Gr4bchxv5
- habibur 3y ago#include <stdio.h> #include <stdlib.h> int main(){ int same=0; int moved=0; char* temp=malloc(16); for(int i=0; i<10000; i++){ char* temp2=realloc(temp,(i+2)*16); if(temp!=temp2){ moved++; temp=temp2; } else same++; } printf("ptr moved %d, reused %d times\n",moved,same); } Tried the above. Ptr moved 7 times and is reused 9993 times. But, what you want to test is what you identify as your need. No point in explaining more.