Handling unsigned overflow of size_t

From: Adam Warner (usenet_at_consulting.net.nz)
Date: 01/07/05


Date: Fri, 07 Jan 2005 22:18:47 +1300

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



Relevant Pages

  • Re: How can I unlock a locked computer?
    ... The simplest way is probably to turn off power to the PC. ... on/off switch really justs sends a request to the motherboard to reboot. ... KNOPPIX is also available as a DVD ISO image, ... > How do I unlock a computer? ...
    (microsoft.public.windowsxp.basics)
  • Re: bungled shooting of Brazilian
    ... Whoever the fuck *they* are. ... > to aid the civil power' has obviously already been made. ... request had to be made publicly by a magistrate. ... this sort of police state hidden power stuff is ...
    (sci.military.naval)
  • Re: bungled shooting of Brazilian
    ... >> to aid the civil power' has obviously already been made. ... >request had to be made publicly by a magistrate. ... >Government can do whatever the fuck it likes. ... this sort of police state hidden power stuff is ...
    (sci.military.naval)
  • Re: [PATCH 0/4] (RESEND) ext3[34] barrier changes
    ... after power cycle read back to see what was and wasn't written. ... fcntlfor applications to request a commit to platter, ... I don't know if MacOS X uses barriers for filesystem ... underlying devices implement barriers with flush. ...
    (Linux-Kernel)
  • Re: Intent
    ... - if we would not receive what we would request, ... the bad, non-collaborating, greedy company who wants nothing but to cash ... Censorship is almost always because of fear or to avoid lose of power. ...
    (borland.public.delphi.non-technical)