]> pd.if.org Git - pdclib.old/blobdiff - functions/stdlib/realloc.c
* Change the style of inclusion of the internal/ headers. Modern preprocessors
[pdclib.old] / functions / stdlib / realloc.c
index c1ba38f4d1cd2b674aa0ae5013ff0ebf54070379..099ad5dd170ea1251c4562d62bf70a295102bcc6 100644 (file)
 
 void * realloc( void * ptr, size_t size )
 {
+    void * newptr = NULL;
     if ( ptr == NULL )
     {
         return malloc( size );
     }
+    if ( size > 0 )
     {
-    struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) );
-    if ( baseptr->size >= size )
-    {
-        return ptr;
-    }
-    else
-    {
-        void * newptr = malloc( size );
-        memcpy( newptr, ptr, baseptr->size );
-        free( ptr );
-        return newptr;
+        struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) );
+        if ( baseptr->size >= size )
+        {
+            /* Current memnode is large enough; nothing to do. */
+            return ptr;
+        }
+        else
+        {
+            /* Get larger memnode and copy over contents. */
+            if ( ( newptr = malloc( size ) ) == NULL )
+            {
+                return NULL;
+            }
+            memcpy( newptr, ptr, baseptr->size );
+        }
     }
-    }
-    return NULL;
+    free( ptr );
+    return newptr;
 }
 
 #endif
@@ -49,3 +55,4 @@ int main( void )
 }
 
 #endif
+