]> pd.if.org Git - pdclib/blobdiff - functions/stdlib/realloc.c
Re-import from Subversion.
[pdclib] / functions / stdlib / realloc.c
index ae11da5c2cba6a509d97042dc8f4612fe42ca8fc..93a2aa418d2280d0853bf7cae2ee474abd8b0081 100644 (file)
@@ -1,32 +1,71 @@
-// ----------------------------------------------------------------------------
-// $Id$
-// ----------------------------------------------------------------------------
-// Public Domain C Library - http://pdclib.sourceforge.net
-// This code is Public Domain. Use, modify, and redistribute at will.
-// ----------------------------------------------------------------------------
+/* ----------------------------------------------------------------------------
+ * $Id$
+ * ----------------------------------------------------------------------------
+ * Public Domain C Library - http://pdclib.sourceforge.net
+ * This code is Public Domain. Use, modify, and redistribute at will.
+ * --------------------------------------------------------------------------*/
 
 void * realloc( void * ptr, size_t size ) { /* TODO */ };
 
-/* PDPC code - unreviewed
+/* PDPC code - assumes size_t of memory chunk at offset -4.
 {
-    char *newptr;
+    char * newptr;
     size_t oldsize;
-    
-    newptr = malloc(size);
-    if (newptr == NULL)
+
+    if ( ( newptr = malloc(size) ) != NULL )
     {
-        return (NULL);
+        if ( ptr != NULL )
+        {
+            // reading size information from hidden chunk header
+            oldsize = * (size_t *) ( (char *) ptr - 4 );
+            // correctly handle *down*sizing as well as *up*sizing
+            memcpy( newptr, ptr, ( oldsize < size ) ? oldsize : size );
+            free( ptr );
+        }
     }
-    if (ptr != NULL)
+    return ( newptr );
+}
+*/
+
+/* Thomas "Beyond Infinity" Kreitner's code - unchecked, unoptimized
+{
+    uint_t found = 0;
+    uint_t length;
+    chunk_t * new;
+    chunk_t * chunk;
+    // searching the block to-be-allocated
+    chunk = used_mem.start;
+    while ( ! found && ( chunk->next != NULL )
     {
-        oldsize = *(size_t *)((char *)ptr - 4);
-        if (oldsize < size)
+        if ( chunk->address == ptr )
+        {
+            found++;
+        }
+        else
         {
-            size = oldsize;
+            chunk=chunk->next;
         }
-        memcpy(newptr, ptr, size);
-        free(ptr);
     }
-    return (newptr);
+    if ( found )
+    {
+        length = chunk->length;
+        // allocate new memory area
+        if ( ( new = (void *) malloc( size ) ) != NULL )
+        {
+            // copy the data
+            memcpy( ptr, new, length );
+            // release the old memory
+            free( ptr );
+        }
+        else
+        {
+            new = NULL;
+        }
+    }
+    else
+    {
+        new = NULL;
+    }
+    return new;
 }
 */