A
Andreas Schmitt
Hi,
I recently worked on an open source project and tried to make on of the
arrays they are using dynamically allocated to get rid of the max size.
I used the realloc instead of the usual C++ new and delete because they
asked me to stick to their "coding style"
Well whatever..
here's what I wrote:
Messages = (MMessage*)realloc( Messages, sizeof(MMessage) *
(m_num_messages + Num_builtin_messages) + 1 );
And here is one comment that came as a result of this:
"If the goal is to make it properly dynamic and he is actually just
adding one element, that is wrong. You always need to allocate in
batches to prevent memory fragmentation. Always increment by 5 or 10 at
the least, some const value, and keep track of the actual size of the
array so that you only have to go up in size when you really need it."
My question now.. from my undertanding, an array is always allocated as
N consecutive blocks of memory to hold its items. How can this cause
memory fragmentation, no matter how small the increase in a reallocation
is...?
I recently worked on an open source project and tried to make on of the
arrays they are using dynamically allocated to get rid of the max size.
I used the realloc instead of the usual C++ new and delete because they
asked me to stick to their "coding style"
Well whatever..
here's what I wrote:
Messages = (MMessage*)realloc( Messages, sizeof(MMessage) *
(m_num_messages + Num_builtin_messages) + 1 );
And here is one comment that came as a result of this:
"If the goal is to make it properly dynamic and he is actually just
adding one element, that is wrong. You always need to allocate in
batches to prevent memory fragmentation. Always increment by 5 or 10 at
the least, some const value, and keep track of the actual size of the
array so that you only have to go up in size when you really need it."
My question now.. from my undertanding, an array is always allocated as
N consecutive blocks of memory to hold its items. How can this cause
memory fragmentation, no matter how small the increase in a reallocation
is...?