[scponly] Re: scponly bug

Karl DeBisschop kdebisschop at alert.infoplease.com
Tue Sep 17 17:52:30 EDT 2002


On Tue, 2002-09-17 at 14:26, joe wrote:
> 
> regarding realloc, you're right that the free before the exit is probably
> not neccesary, however, to explain the origin of this code, keep reading:
> 
> the original code in helper.c:
>                 if (NULL == (temp = realloc (outbuf, newlen)))
>                 {
>                         perror("realloc");
>                         if (outbuf)
>                                 free(outbuf);
>                         exit(-1);
>                 }
>                 outbuf=temp;
>                 temp=NULL;
> 
> the openbsd realloc() manpage:
>      When using realloc() one must be careful to avoid the following
> idiom:
> 
>            if ((p = realloc(p, nsize)) == NULL)
>                    return NULL;
> 
>      In most cases, this will result in a leak of memory.  As stated
> earlier,
>      a return value of NULL indicates that the old object still remains
> allocated.  
>
> Better code looks like this:
> 
>            if ((p2 = realloc(p, nsize)) == NULL) {
>                    if (p)
>                            free(p);
>                    p = NULL;
>                    return NULL;
>            }
>            p = p2;
> 

Interesting.

This is from the linux man page:

       realloc()  changes the size of the memory block pointed to
       by ptr to size bytes.  The contents will be  unchanged  to
       the minimum of the old and new sizes; newly allocated mem-
       ory will be uninitialized.  If ptr is NULL,  the  call  is
       equivalent  to malloc(size); if size is equal to zero, the
       call is equivalent to free(ptr).  Unless ptr is  NULL,  it
       must  have  been  returned by an earlier call to malloc(),
       calloc() or realloc().

So if the linux man page is correct, I see no other way to read it
except to believe that if newlen is zero, then outbuf has already been
freed and calling free again will result in a memory violation.

Note that the invocation of realloc does not change the value of outbuf
(ever), unless it modifies its args (hmmm...maybe it does). So if newlen
is zero, outbuf still has a value and freeing that value will be a
violation. In other words, unless realloc changes its args, then you
cannot test against its value after the realloc. You might be able to
test against the contents of outbuf, if you can assume that those memory
locations have been cleared, but I'm not sure you can assume that
either.

R&R says 'realloc returns a pointer to the NEW space' (emphasis mine).
Which would seem to suggest that that the OepnBSD man page may be in
error.

At the very least, it does not appear that there is great agreement
between the man pages. Have you look at POSIX or ANSI?

-- 
Karl DeBisschop <kdebisschop at alert.infoplease.com>





More information about the scponly mailing list