メモリ確保時のサイズを修正
[YACASL2.git] / src / cerr.c
1 #include "cerr.h"
2
3 /* エラー番号 */
4 int cerrno = 0;
5
6 /* エラーメッセージ */
7 char *cerrmsg;
8
9 /* エラーリスト */
10 CERRLIST *cerr;
11
12 /* エラーリストを作成する */
13 bool addcerrlist(int newerrc, CERRARRAY newerrv[])
14 {
15     int i;
16     CERRLIST *p, *q;
17
18     assert(newerrc > 0 && newerrv != NULL);
19     if(cerr != NULL) {
20         for(p = cerr; p != NULL; p = p->next) {
21             q = p;
22         }
23         if((p = q->next = malloc(sizeof(CERRLIST))) == NULL) {
24             goto addcerrlisterr;
25         }
26     } else if((p = cerr = malloc(sizeof(CERRLIST))) == NULL) {
27         goto addcerrlisterr;
28     }
29     for(i = 0; i < newerrc; i++) {
30         p->err = &(newerrv[i]);
31         if((p->next = malloc(sizeof(CERRLIST))) == NULL) {
32             goto addcerrlisterr;
33         }
34         q = p;
35         p = p->next;
36     }
37     q->next = NULL;
38     return true;
39 addcerrlisterr:
40     fprintf(stderr, "addcerrlist: cannot allocate memory\n");
41     exit(-1);
42 }
43
44 /* エラー番号とエラーメッセージを設定する */
45 void setcerr(int num, const char *str)
46 {
47     cerrno = num;
48     cerrmsg = malloc(CERRMSGSIZE + 1);
49     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
50         sprintf(cerrmsg, "%s: %s", str, getcerrmsg(cerrno));
51     } else {
52         strcpy(cerrmsg, getcerrmsg(cerrno));
53     }
54 }
55
56 /* リストから、エラー番号に対応するメッセージを返す */
57 char *getcerrmsg(int num)
58 {
59     CERRLIST *p;
60
61     for(p = cerr; p != NULL; p = p->next) {
62         if(num == p->err->num) {
63             return p->err->msg;
64         }
65     }
66     return "unkown error";
67 }
68
69 /* エラーを解放する */
70 void freecerr()
71 {
72     assert(cerrno > 0);
73     cerrno = 0;
74     if(strlen(cerrmsg) > 0) {
75         free(cerrmsg);
76     }
77 }