Handling unsigned overflow of size_t

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
that's offset from 0x00000000. 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
 
P

pete

Adam said:
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?

No.

Keep track of the argument from the latest call to malloc().
If twice the old argument, is less than the old argument,
then you're done.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top