NetBSD-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: xmalloc.c issue (after xfree(cp), cp is used in irealloc())



On May 14,  6:08pm, amolpise15%gmail.com@localhost (amol pise) wrote:
-- Subject: xmalloc.c issue (after xfree(cp), cp is used in irealloc())

| Hi,
| 
| I used netBSD-5 for my system and during code observation
| I have a seen in the  xmalloc.c the pointer "cp"  is used after xfree(cp).
| How it is possible ? please see the code below
| 
| # cat src/libexec/ld.elf_so/xmalloc.c
| {{{
| 332 static void *
| 333 irealloc(void *cp, size_t nbytes)
| 334 {
| 335         register u_int onb;
| 336         register int i;
| 337         union overhead *op;
| 338         char *res;
| :
| :
| <snip>
| 358         /* avoid the copy if same size block */
| 359         if (i) {
| 360                 i = 1 << (i + 2);
| 361                 if (i < pagesz)
| 362                         i -= sizeof (*op) + RSLOP;
| 363                 else
| 364                         i += pagesz - sizeof (*op) - RSLOP;
| 365         }
| 366         if (nbytes <= onb && nbytes > i) {
| 367 #ifdef RCHECK
| 368                 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
| 369                 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
| 370 #endif
| 371                 return(cp);
| 372         } else
| 373                 xfree(cp);
| 374         if ((res = imalloc(nbytes)) == NULL)
| 375                 return (NULL);
| 376         if (cp != res)          /* common optimization if "compacting" */
| 377                 memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
| 378         return (res);
| 379 }
| }}}
| 
| in the above code at line:373 xfree(cp) is done and at line:377 cp is used to
| copy to the result. I think this is not OK. Shall I file PR for this.
| 
| Please tell me if there are any issues.
| 
| Waiting for the reply.

The code is clearly wrong. I guess we are lucky that it does not get
invoked. Here's a fix.

christos

Index: xmalloc.c
===================================================================
RCS file: /cvsroot/src/libexec/ld.elf_so/xmalloc.c,v
retrieving revision 1.11
diff -u -u -r1.11 xmalloc.c
--- xmalloc.c   25 May 2011 14:41:46 -0000      1.11
+++ xmalloc.c   14 May 2012 16:03:13 -0000
@@ -369,12 +369,13 @@
                *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
 #endif
                return(cp);
-       } else
-               xfree(cp);
+       }
        if ((res = imalloc(nbytes)) == NULL)
                return (NULL);
-       if (cp != res)          /* common optimization if "compacting" */
+       if (cp != res) {        /* common optimization if "compacting" */
                memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
+               xfree(cp);
+       }
        return (res);
 }
 



Home | Main Index | Thread Index | Old Index