A
Adam Warner
Hi all!
When dealing with dynamically adjusted objects are you ever concerned that
you'll double the requested size of the object and overflow size_t so that
the requested size e.g. becomes zero?
I realise it's extremely likely that all memory and address space will be
exhausted before one is able to malloc an object close to the maximum of
size_t. I'd just like to know best practice.
Let's consider a 32-bit address space with an object 0x80000000 size_t.
The algorithm is to always double the size of the object. When you compute
the new size of the object it will be zero.
To avoid this one could start with a size_t one less than a power of two
and always add one before doubling. Afterwards subtracting one again.
So the object above would be 0x7FFFFFFF size_t. One adds 1 (0x80000000),
doubles it (0x00000000) and subtracts 1 (0xFFFFFFFF) so that realloc
doesn't have a hope of succeeding and will return NULL to check for
instead of undefined behaviour resulting from reallocating a smaller
object.
On the other hand it feels odd to request a new size each time that is not
a power of two. Who ever allocates 2^n-1 bytes instead of 2^n?
Thanks for your advice.
Regards,
Adam
When dealing with dynamically adjusted objects are you ever concerned that
you'll double the requested size of the object and overflow size_t so that
the requested size e.g. becomes zero?
I realise it's extremely likely that all memory and address space will be
exhausted before one is able to malloc an object close to the maximum of
size_t. I'd just like to know best practice.
Let's consider a 32-bit address space with an object 0x80000000 size_t.
The algorithm is to always double the size of the object. When you compute
the new size of the object it will be zero.
To avoid this one could start with a size_t one less than a power of two
and always add one before doubling. Afterwards subtracting one again.
So the object above would be 0x7FFFFFFF size_t. One adds 1 (0x80000000),
doubles it (0x00000000) and subtracts 1 (0xFFFFFFFF) so that realloc
doesn't have a hope of succeeding and will return NULL to check for
instead of undefined behaviour resulting from reallocating a smaller
object.
On the other hand it feels odd to request a new size each time that is not
a power of two. Who ever allocates 2^n-1 bytes instead of 2^n?
Thanks for your advice.
Regards,
Adam