malloc failures in java/util/zip/Deflater

Roman Kennke Roman.Kennke at Sun.COM
Wed Jul 8 20:01:46 UTC 2009


Hi Mario,


> >> According to the specs, malloc may return either a valid pointer that
> >> can be passed to free, or NULL, while generally NULL is considered to be
> >> a failure. Linux and Solaris, albeit non specifying it, return always a
> >> valid pointer, as far as I know
> >
> > I think NULL is returned in an out of memory situation, which is very
> > rare on modern OSes, but I think it's still possible. The right thing to
> > do here is check for NULL and (try to) throw an OOME. Which is what is
> > beeing done already (AFAICS). What are you trying to solve by
> > additionally checking for len>  0?
> >
> > /Roman
> 
> Hi Roman,
> 
> The OutOfMemory is thrown correctly in case of failure (it wasn't up to 
> some builds ago, though :).
> 
> The problem is when passing a 0 length argument to malloc (from the man 
> page):
> 
> malloc()  allocates  size  bytes and returns a pointer to the allocated
>            memory.  The memory is not  cleared.   If  size  is  0, then
>            malloc() returns  either  NULL, or a unique pointer value
>            that can later be successfully passed to free().
> 
> Linux and Solaris AFAIK return a pointer to valid memory, but this is 
> not specified, and the code only checks for NULL as in failure. So it 
> may be the case that this changes in future. In my case I have a 
> not-so-modern OS that returns NULL in such case.
> 
> So, to decide if we have a memory error or not, we need the additional 
> len > 0 check.

Ah, I see! The len==0 case is not a failure, but some OSes return NULL
anyway, running into an OOME even when there's no error? Now that you
don't throw OOME in these cases, you might want to check the pointer
later so that you don't get a segfault when you pass this NULL pointer
to other functions like free(). (uhm .. TARGET_FREE_UNSAFE? oops,
internal joke... ;-). )

/Roman





More information about the core-libs-dev mailing list