Re: [PATCH 2/4] short circuit out of a few places where we would allocate zero bytes

From: Junio C Hamano <junkio@cox.net>
Date: 2005-12-28 16:07:28
Linus Torvalds <torvalds@osdl.org> writes:

> That said, I think that would be preferable to changing the source code to 
> unnecessarily avoid zero-sized allocations.

Yes, that has essentially been the plan (according to the
discussion lead to 7e4a2a848377241b8fb4f624d1151bbf2f8d5814
commit on the list).

After eradicating zero-sized allocations where that change makes
the overall code cleaner (which Johannes and Eric did most of
the heavylifting and I think mostly done), we would apply
something like this, instead of doing x*alloc(size ? size : 1)
at the calling site.

About die(), I think the current code structure is fine.  If we
were doing a library, propagating NULL from C library *alloc()
back to our caller and having the caller deal with it is the
right thing, but most of the callers of x*alloc() are our main
programs and there aren't much they can do when we run out of
memory.

---
diff --git a/git-compat-util.h b/git-compat-util.h
index 0c98c99..a71728e 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -63,6 +63,8 @@ extern char *gitstrcasestr(const char *h
 static inline void *xmalloc(size_t size)
 {
 	void *ret = malloc(size);
+	if (!ret && !size)
+		ret = malloc(1); /* funny c library */
 	if (!ret)
 		die("Out of memory, malloc failed");
 	return ret;
@@ -71,6 +73,8 @@ static inline void *xmalloc(size_t size)
 static inline void *xrealloc(void *ptr, size_t size)
 {
 	void *ret = realloc(ptr, size);
+	if (!ret && !size)
+		ret = realloc(ptr, 1); /* funny c library */
 	if (!ret)
 		die("Out of memory, realloc failed");
 	return ret;
@@ -79,6 +83,8 @@ static inline void *xrealloc(void *ptr, 
 static inline void *xcalloc(size_t nmemb, size_t size)
 {
 	void *ret = calloc(nmemb, size);
+	if (!ret && (!nmemb || !size))
+		ret = calloc(1, 1); /* funny c library */
 	if (!ret)
 		die("Out of memory, calloc failed");
 	return ret;



-
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Received on Wed Dec 28 16:10:25 2005

This archive was generated by hypermail 2.1.8 : 2005-12-28 16:10:33 EST