X-Git-Url: http://j8takagi.net/cgi-bin/gitweb.cgi?p=YACASL2.git;a=blobdiff_plain;f=src%2Fcmem.c;h=e921bb08f4678bf2c783e0e0621a303b34ea2cd5;hp=ef7a9ddb75e0fe1303aabcdf8084e586ddccdd4f;hb=58b56a6373dbd2b2ce8d30f7661ff15f584fb03f;hpb=18f59ad1ab72e5dea0386bd7811c3fcfb4cd7805 diff --git a/src/cmem.c b/src/cmem.c index ef7a9dd..e921bb0 100644 --- a/src/cmem.c +++ b/src/cmem.c @@ -2,7 +2,7 @@ void *malloc_chk(size_t size, const char *tag) { - void *p; + void *p = NULL; if((p = malloc(size)) == NULL) { fprintf(stderr, "%s: cannot allocate memory\n", tag); @@ -11,9 +11,9 @@ void *malloc_chk(size_t size, const char *tag) return memset(p, 0, size); } -void *calloc_chk(size_t nmemb, size_t size, char *tag) +void *calloc_chk(size_t nmemb, size_t size, const char *tag) { - void *p; + void *p = NULL; if((p = calloc(nmemb, size)) == NULL) { fprintf(stderr, "%s: cannot allocate memory\n", tag); @@ -22,23 +22,37 @@ void *calloc_chk(size_t nmemb, size_t size, char *tag) return p; } -char *strdup_chk(const char *s, char *tag) +char *strdup_chk(const char *s, const char *tag) { assert(s != NULL); - char *t; + char *t = NULL; t = malloc_chk(strlen(s) + 1, tag); strcpy(t, s); return t; } -char *strndup_chk(const char *s, size_t len, char *tag) +char *strndup_chk(const char *s, size_t len, const char *tag) { assert(s != NULL); - char *t; - - t = malloc_chk(len + 1, tag); - strncpy(t, s, len); - t[len] = '\0'; + char *t = NULL; + + if(len < strlen(s)) { + t = malloc_chk(len + 1, tag); + strncpy(t, s, len); + t[len] = '\0'; + } else { + t = strdup_chk(s, tag); + } return t; } + +char *strip_end(char *s) +{ + int i; + i = strlen(s) - 1; + while(i > 0 && (s[i] == '\n' || s[i] == ' ' || s[i] == '\t')) { + s[i--] = '\0'; + } + return s; +}