メモリリークの修正
[YACASL2.git] / src / cmem.c
1 #include "cmem.h"
2
3 void *malloc_chk(size_t size, const char *tag)
4 {
5     void *p = NULL;
6
7     if((p = malloc(size)) == NULL) {
8         fprintf(stderr, "%s: cannot allocate memory\n", tag);
9         exit(1);
10     }
11     return memset(p, 0, size);
12 }
13
14 void *calloc_chk(size_t nmemb, size_t size, const char *tag)
15 {
16     void *p = NULL;
17
18     if((p = calloc(nmemb, size)) == NULL) {
19         fprintf(stderr, "%s: cannot allocate memory\n", tag);
20         exit(1);
21     }
22     return p;
23 }
24
25 char *strdup_chk(const char *s, const char *tag)
26 {
27     assert(s != NULL);
28     char *t = NULL;
29
30     t = malloc_chk(strlen(s) + 1, tag);
31     strcpy(t, s);
32     return t;
33 }
34
35 char *strndup_chk(const char *s, size_t len, const char *tag)
36 {
37     assert(s != NULL);
38     char *t = NULL;
39
40     if(len < strlen(s)) {
41         t = malloc_chk(len + 1, tag);
42         strncpy(t, s, len);
43         t[len] = '\0';
44     } else {
45         t = strdup_chk(s, tag);
46     }
47     return t;
48 }
49
50 char *strip_end(char *s)
51 {
52     int i;
53     i = strlen(s) - 1;
54     while(i > 0 && (s[i] == '\n' || s[i] == ' ' || s[i] == '\t')) {
55         s[i--] = '\0';
56     }
57     return s;
58 }
59
60 char *strip_casl2_comment(char *s)
61 {
62     int i;
63     bool quoting = false;
64
65     for(i = 0; s[i]; i++) {
66         /* 「'」で囲まれた文字列の場合。「''」は無視 */
67         if(s[i] == '\'' && s[i+1] != '\'' && (quoting == false || s[i-1] != '\'')) {
68             quoting = !quoting;
69         /* 「'」で囲まれた文字列でない場合、文字列末尾の「;」以降を削除 */
70         } else if(quoting == false && s[i] == ';') {
71             s[i] = '\0';
72             break;
73         }
74     }
75     return s;
76 }