comparison array.c @ 2:9c1cecba517c

Make arrays crash on malloc failure.
author David A. Holland
date Sun, 19 Dec 2010 16:51:21 -0500
parents 411b28d78483
children b156910b59b2
comparison
equal deleted inserted replaced
1:411b28d78483 2:9c1cecba517c
36 struct array * 36 struct array *
37 array_create(void) 37 array_create(void)
38 { 38 {
39 struct array *a; 39 struct array *a;
40 40
41 a = malloc(sizeof(*a)); 41 a = domalloc(sizeof(*a));
42 if (a != NULL) { 42 array_init(a);
43 array_init(a);
44 }
45 return a; 43 return a;
46 } 44 }
47 45
48 void 46 void
49 array_destroy(struct array *a) 47 array_destroy(struct array *a)
67 #ifdef ARRAYS_CHECKED 65 #ifdef ARRAYS_CHECKED
68 a->v = NULL; 66 a->v = NULL;
69 #endif 67 #endif
70 } 68 }
71 69
72 int 70 void
73 array_setsize(struct array *a, unsigned num) 71 array_setsize(struct array *a, unsigned num)
74 { 72 {
75 unsigned newmax; 73 unsigned newmax;
76 void **newptr; 74 void **newptr;
77 75
78 if (num > a->max) { 76 if (num > a->max) {
79 newmax = a->max; 77 newmax = a->max;
80 while (num > newmax) { 78 while (num > newmax) {
81 newmax = newmax ? newmax*2 : 4; 79 newmax = newmax ? newmax*2 : 4;
82 } 80 }
83 newptr = realloc(a->v, newmax*sizeof(*a->v)); 81 newptr = dorealloc(a->v, newmax*sizeof(*a->v));
84 if (newptr == NULL) {
85 return -1;
86 }
87 a->v = newptr; 82 a->v = newptr;
88 a->max = newmax; 83 a->max = newmax;
89 } 84 }
90 a->num = num; 85 a->num = num;
91 return 0;
92 } 86 }
93 87
94 int 88 void
95 array_insert(struct array *a, unsigned index_) 89 array_insert(struct array *a, unsigned index_)
96 { 90 {
97 unsigned movers; 91 unsigned movers;
98 92
99 arrayassert(a->num <= a->max); 93 arrayassert(a->num <= a->max);
100 arrayassert(index_ < a->num); 94 arrayassert(index_ < a->num);
101 95
102 movers = a->num - index_; 96 movers = a->num - index_;
103 97
104 if (array_setsize(a, a->num + 1)) { 98 array_setsize(a, a->num + 1);
105 return -1;
106 }
107 99
108 memmove(a->v + index_+1, a->v + index_, movers*sizeof(*a->v)); 100 memmove(a->v + index_+1, a->v + index_, movers*sizeof(*a->v));
109 return 0;
110 } 101 }
111 102
112 void 103 void
113 array_remove(struct array *a, unsigned index_) 104 array_remove(struct array *a, unsigned index_)
114 { 105 {