Fix a memory leak if parent directory creation failed.
[oweals/busybox.git] / libbb / xfuncs.c
index e7f41aae2b0e070e0bd8a0abc36606cba039854d..eb93bf139d617a3950870cf98737a0e3b0ebb87a 100644 (file)
 #include <unistd.h>
 #include "libbb.h"
 
-/* same conditions as recursive_action */
-#define bb_need_memory_exhausted
-#define BB_DECLARE_EXTERN
-#include "../messages.c"
-
 
 #ifndef DMALLOC
 extern void *xmalloc(size_t size)
@@ -49,7 +44,17 @@ extern void *xmalloc(size_t size)
 
 extern void *xrealloc(void *old, size_t size)
 {
-       void *ptr = realloc(old, size);
+       void *ptr;
+
+       /* SuS2 says "If size is 0 and ptr is not a null pointer, the
+        * object pointed to is freed."  Do that here, in case realloc
+        * returns a NULL, since we don't want to choke in that case. */
+       if (size==0 && old) {
+               free(old);
+               return NULL;
+       }
+
+       ptr = realloc(old, size);
        if (!ptr)
                error_msg_and_die(memory_exhausted);
        return ptr;