2
0
Эх сурвалжийг харах

'realloc' can fail when shrinking a block

According to ISO C, 'realloc' can fail when shrinking a block. If that
happens, 'l_alloc' simply ignores the fail and returns the original
block.
Roberto Ierusalimschy 5 жил өмнө
parent
commit
6d763a2500
1 өөрчлөгдсөн 7 нэмэгдсэн , 2 устгасан
  1. 7 2
      lauxlib.c

+ 7 - 2
lauxlib.c

@@ -1011,8 +1011,13 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
     free(ptr);
     return NULL;
   }
-  else
-    return realloc(ptr, nsize);
+  else {  /* cannot fail when shrinking a block */
+    void *newptr = realloc(ptr, nsize);
+   if (newptr == NULL && ptr != NULL && nsize <= osize)
+     return ptr;  /* keep the original block */
+   else  /* no fail or not shrinking */
+    return newptr;  /* use the new block */
+  }
 }