X-Git-Url: http://git.marmaro.de/?p=mmh;a=blobdiff_plain;f=sbr%2Futils.c;h=ef0ee9738676d018b9c191f3d339cf89593b04ff;hp=fa4cfdb2b3b8e5e97831407f5599327b05fa43e5;hb=eb650f703c26232c0ccce00c9b3dd3f6b6d51dd4;hpb=d29d0d9cef0620e6a7ed0a18462d33c99ecd9da5 diff --git a/sbr/utils.c b/sbr/utils.c index fa4cfdb..ef0ee97 100644 --- a/sbr/utils.c +++ b/sbr/utils.c @@ -22,26 +22,6 @@ #define MAXMSGS 256 /* -** Safely call malloc -*/ -void * -mh_xmalloc(size_t size) -{ - void *memory; - - if (size == 0) { - adios(EX_SOFTWARE, NULL, "Tried to malloc 0 bytes"); - } - - memory = malloc(size); - if (!memory) { - adios(EX_OSERR, NULL, "Malloc failed"); - } - - return memory; -} - -/* ** Safely call realloc */ void * @@ -51,7 +31,7 @@ mh_xrealloc(void *ptr, size_t size) /* Some non-POSIX realloc()s don't cope with realloc(NULL,sz) */ if (!ptr) { - return mh_xcalloc((size_t) 1, size); + return mh_xcalloc(1, size); } if (size == 0) { adios(EX_SOFTWARE, NULL, "Tried to realloc 0 bytes"); @@ -85,6 +65,18 @@ mh_xcalloc(size_t nmemb, size_t size) } /* +** Free a pointer and set it to NULL. +*/ +void +mh_free0(void * ptr) +{ + void ** p; + p = ptr; + free(*p); + *p = NULL; +} + +/* ** Return the present working directory, if the current directory does not ** exist, or is too long, make / the pwd. */ @@ -115,14 +107,14 @@ pwd(void) /* ** add -- If "s1" is NULL, this routine just creates a ** -- copy of "s2" into newly malloc'ed memory. -** -- (use getcpy() instead in this case) +** -- (use mh_xstrdup() instead in this case) ** -- ** -- If "s1" is not NULL, then copy the concatenation ** -- of "s1" and "s2" (note the order) into newly ** -- malloc'ed memory. Then free "s1". */ char * -add(char *s2, char *s1) +add(const char *s2, char *s1) { char *cp; size_t len1 = 0, len2 = 0; @@ -134,12 +126,12 @@ add(char *s2, char *s1) len2 = strlen(s2); } - cp = mh_xmalloc(len1 + len2 + 1); + cp = mh_xcalloc(len1 + len2 + 1, sizeof(char)); /* Copy s1 and free it */ if (s1) { memcpy(cp, s1, len1); - free(s1); + mh_free0(&s1); } /* Copy s2 */ @@ -175,7 +167,7 @@ create_folder(char *folder, int autocreate, void (*done_callback)(int)) if (!getanswer(cp)) { done_callback(EX_CANTCREAT); } - free(cp); + mh_free0(&cp); } else if (autocreate == -1) { /* do not create, so exit */ done_callback(EX_CANTCREAT); @@ -226,3 +218,19 @@ app_msgarg(struct msgs_array *msgs, char *cp) } msgs->msgs[msgs->size++] = cp; } + +/* +** mh_xstrdup() is a wrapper of strdup() to replace getcpy(). It returns +** a copy of its argument if this is nonnull; otherwise, it returns a +** string of length 0. +*/ +char * +mh_xstrdup(char * s) +{ + char * tmp; + tmp = strdup(s ? s : ""); + if (!tmp) { + adios(EX_OSERR, "strdup", "can't copy string"); + } + return tmp; +}