3085ea6303a2d3c714c958477e2d2d4a393bb8c8
[YACASL2.git] / src / cmem.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <stdbool.h>
6 #include "cmem.h"
7
8 /**
9  * mallocを実行し、0で初期化\n
10  * メモリを確保できない場合はエラーを出力して終了
11  */
12 void *malloc_chk(size_t size, char *tag)
13 {
14     void *p;
15
16     if((p = malloc(size)) == NULL) {
17         fprintf(stderr, "%s: cannot allocate memory\n", tag);
18         exit(1);
19     }
20     return memset(p, 0, size);
21 }
22
23 /**
24  * callocを実行\n
25  * メモリを確保できない場合はエラーを出力して終了
26  */
27 void *calloc_chk(size_t nmemb, size_t size, char *tag)
28 {
29     void *p;
30
31     if((p = calloc(nmemb, size)) == NULL) {
32         fprintf(stderr, "%s: cannot allocate memory\n", tag);
33         exit(1);
34     }
35     return p;
36 }
37
38 /**
39  * malloc_chkを実行してメモリを確保し、コピーした文字列を返す
40  */
41 char *strdup_chk(const char *s, char *tag)
42 {
43     assert(s != NULL);
44     char *t;
45
46     t = malloc_chk(strlen(s) + 1, tag);
47     strcpy(t, s);
48     return t;
49 }