diff options
author | Vicent Marti <tanoku@gmail.com> | 2011-05-05 01:20:27 +0300 |
---|---|---|
committer | Vicent Marti <tanoku@gmail.com> | 2011-05-09 21:58:02 +0300 |
commit | 3f53c97113deb986b58aac8bb89f76b47e76507b (patch) | |
tree | 07035e51be600f40b6644343ff6ac246bab2bd02 | |
parent | 02f9e637a1d282d03ce3362e7c3467e73c87bf2e (diff) | |
download | libgit2-3f53c97113deb986b58aac8bb89f76b47e76507b.tar.gz |
errors: Set error messages on memory allocation
-rw-r--r-- | src/common.h | 4 | ||||
-rw-r--r-- | src/util.h | 43 |
2 files changed, 36 insertions, 11 deletions
diff --git a/src/common.h b/src/common.h index b3f5253a9..351d6696f 100644 --- a/src/common.h +++ b/src/common.h @@ -50,12 +50,12 @@ typedef SSIZE_T ssize_t; #include "git2/common.h" #include "git2/types.h" -#include "util.h" #include "thread-utils.h" #include "bswap.h" #define GIT_PATH_MAX 4096 - extern int git__error(int error, const char *, ...) GIT_FORMAT_PRINTF(2, 3); +#include "util.h" + #endif /* INCLUDE_common_h__ */ diff --git a/src/util.h b/src/util.h index 3c606493f..f5f0b8662 100644 --- a/src/util.h +++ b/src/util.h @@ -6,16 +6,41 @@ #define MSB(x, bits) ((x) & (~0ULL << (bitsizeof(x) - (bits)))) /* - * Don't wrap malloc/calloc. - * Use the default versions in glibc, and make - * sure that any methods that allocate memory - * return a GIT_ENOMEM error when allocation - * fails. + * Custom memory allocation wrappers + * that set error code and error message + * on allocation failure */ -#define git__malloc malloc -#define git__calloc calloc -#define git__realloc realloc -#define git__strdup strdup +GIT_INLINE(void *) git__malloc(size_t len) +{ + void *ptr = malloc(len); + if (!ptr) + git__error(GIT_ENOMEM, "Out of memory. Failed to allocate %d bytes.", (int)len); + return ptr; +} + +GIT_INLINE(void *) git__calloc(size_t nelem, size_t elsize) +{ + void *ptr = calloc(nelem, elsize); + if (!ptr) + git__error(GIT_ENOMEM, "Out of memory. Failed to allocate %d bytes.", (int)elsize); + return ptr; +} + +GIT_INLINE(char *) git__strdup(const char *str) +{ + char *ptr = strdup(str); + if (!ptr) + git__error(GIT_ENOMEM, "Out of memory. Failed to duplicate string"); + return ptr; +} + +GIT_INLINE(void *) git__realloc(void *ptr, size_t size) +{ + void *new_ptr = realloc(ptr, size); + if (!new_ptr) + git__error(GIT_ENOMEM, "Out of memory. Failed to allocate %d bytes.", (int)size); + return new_ptr; +} extern int git__fmt(char *, size_t, const char *, ...) GIT_FORMAT_PRINTF(3, 4); |