メモリ管理の改善
[YACASL2.git] / src / cerr.c
1 #include "cerr.h"
2
3 /* エラーの初期化 */
4 void cerr_init()
5 {
6     cerr = malloc_chk(sizeof(CERR), "cerr");
7     cerr->num = 0;
8 }
9
10 /* 現在のエラー */
11 CERR *cerr;
12
13 /* エラーリスト */
14 CERRLIST *cerrlist;
15
16 /* エラーリストを作成・追加する */
17 bool addcerrlist(int newerrc, CERR newerrv[])
18 {
19     int i;
20     CERRLIST *p, *q;
21
22     assert(newerrc > 0 && newerrv != NULL);
23     if(cerrlist == NULL) {
24         p = cerrlist = malloc_chk(sizeof(CERRLIST), "cerrlist");
25     } else {
26         for(p = cerrlist; p != NULL; p = p->next) {
27             q = p;
28         }
29         p = q->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
30     }
31     for(i = 0; i < newerrc; i++) {
32         p->cerr = &(newerrv[i]);
33         p->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
34         q = p;
35         p = p->next;
36     }
37     q->next = NULL;
38     return true;
39 }
40
41 /* 現在のエラーを設定する */
42 void setcerr(int num, const char *str)
43 {
44     /* 現在のエラー番号を設定  */
45     cerr->num = num;
46     /* 現在のエラーメッセージを設定 */
47     cerr->msg = malloc_chk(CERRMSGSIZE + 1, "cerr.msg");
48     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
49         sprintf(cerr->msg, "%s: %s", str, getcerrmsg(cerr->num));
50     } else {
51         strcpy(cerr->msg, getcerrmsg(cerr->num));
52     }
53 }
54
55 /* エラーリストから、エラー番号に対応するメッセージを返す */
56 char *getcerrmsg(int num)
57 {
58     CERRLIST *p;
59
60     for(p = cerrlist; p != NULL; p = p->next) {
61         if(num == p->cerr->num) {
62             return p->cerr->msg;
63         }
64     }
65     return "unknown error";
66 }
67
68 /* エラーリストと現在のエラーを解放する */
69 void freecerr()
70 {
71     CERRLIST *p = cerrlist, *q;
72
73     /* エラーリストを解放 */
74     while(p != NULL) {
75         q = p->next;
76         free_chk(p, "freecerr.p");
77         p = q;
78     }
79     /* 現在のエラーメッセージを解放 */
80     free_chk(cerr->msg, "cerr.msg");
81     /* 現在のエラーを解放 */
82     free_chk(cerr, "cerr");
83 }