bug-gnulib
[Top][All Lists]
Advanced

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

realloc buggy?


From: Simon Josefsson
Subject: realloc buggy?
Date: Thu, 01 Jun 2006 10:03:12 +0200
User-agent: Gnus/5.110006 (No Gnus v0.6) Emacs/22.0.50 (gnu/linux)

For read-file, I looked at realloc, and can't help but feel it is
buggy.  Here is the function:

void *
rpl_realloc (void *p, size_t n)
{
  if (n == 0)
    {
      n = 1;

      /* In theory realloc might fail, so don't rely on it to free.  */
      free (p);
      p = NULL;
    }

  if (p == NULL)
    return malloc (n);
  return realloc (p, n);
}

If, for a non-NULL p, realloc (p, 0) returns NULL, i.e., if the malloc
fails, then p has been freed, which doesn't seem right?  If realloc
returns NULL, the pointer should not have been freed, according to my
realloc(3):

  If realloc()
       fails the original block is left untouched; it is not freed or moved.

What about this instead?

void *
rpl_realloc (void *p, size_t n)
{
  if (n == 0)
    {
      void *tmp = malloc (1);
      if (!tmp)
        return NULL;

      free (p);
      return tmp;
    }

  if (p == NULL)
    return malloc (n);
  return realloc (p, n);
}

/Simon

2006-06-01  Simon Josefsson  <address@hidden>

        * realloc.c (rpl_realloc): For non-NULL pointers and zero length,
        don't free until we have succesfully allocated a buffer.

--- realloc.c   20 Sep 2005 11:12:17 +0200      1.12
+++ realloc.c   01 Jun 2006 09:57:57 +0200      
@@ -1,5 +1,5 @@
 /* realloc() function that is glibc compatible.
-   Copyright (C) 1997, 2003, 2004 Free Software Foundation, Inc.
+   Copyright (C) 1997, 2003, 2004, 2006 Free Software Foundation, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -33,11 +33,12 @@
 {
   if (n == 0)
     {
-      n = 1;
+      void *tmp = malloc (1);
+      if (!tmp)
+       return NULL;
 
-      /* In theory realloc might fail, so don't rely on it to free.  */
       free (p);
-      p = NULL;
+      return tmp;
     }
 
   if (p == NULL)




reply via email to

[Prev in Thread] Current Thread [Next in Thread]