メモリリークの修正
[YACASL2.git] / src / cerr.c
1 #include "cerr.h"
2
3 void cerr_init()
4 {
5     cerr = malloc_chk(sizeof(CERR), "cerr");
6     cerr->num = 0;
7 }
8
9 CERR *cerr;
10
11 CERRLIST *cerrlist = NULL;
12
13 void addcerrlist(int cerrc, CERR cerrv[])
14 {
15     int i;
16     CERRLIST *p = NULL, *q = malloc_chk(sizeof(CERRLIST), "cerrlist");
17
18     assert(cerrc > 0 && cerrv != NULL);
19     for(i = 0; i < cerrc; i++) {
20         if(p == NULL) {
21             p = q;
22         } else {
23             p = p->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
24         }
25         p->cerr = &cerrv[i];
26         p->next = NULL;
27     }
28     p->next = cerrlist;
29     cerrlist = q;
30 }
31
32 void printcerrlist()
33 {
34     CERRLIST *p;
35
36     if(cerrlist == NULL) {
37         puts("error list is null.");
38     } else {
39         for(p = cerrlist; p != NULL; p = p->next) {
40             printf("%d: %s\n", p->cerr->num, p->cerr->msg);
41         }
42     }
43 }
44
45 void setcerr(int num, const char *str)
46 {
47     /* 現在のエラー番号を設定  */
48     cerr->num = num;
49     /* 現在のエラーメッセージを設定 */
50     cerr->msg = malloc_chk(CERRMSGSIZE + 1, "cerr.msg");
51     if(0 < strlen(str) && strlen(str) <= CERRSTRSIZE) {
52         sprintf(cerr->msg, "%s: %s", str, getcerrmsg(cerr->num));
53     } else {
54         strcpy(cerr->msg, getcerrmsg(cerr->num));
55     }
56 }
57
58 char *getcerrmsg(int num)
59 {
60     CERRLIST *p;
61     char *msg = "unknown error";
62
63     for(p = cerrlist; p != NULL; p = p->next) {
64         if(num == p->cerr->num) {
65             msg = p->cerr->msg;
66             break;
67         }
68     }
69     return msg;
70 }
71
72 void freecerr()
73 {
74     CERRLIST *p = cerrlist, *q;
75
76     /* 現在のエラーメッセージを解放 */
77     FREE(cerr->msg);
78     /* 現在のエラーを解放 */
79     FREE(cerr);
80     /* エラーリストを解放 */
81     for(p = cerrlist; p != NULL; p = q) {
82         q = p->next;
83         FREE(p);
84     }
85 }