Skip to content

Commit e7db8ce

Browse files
committed
Missing error handling for the vstring API.
Some things here should be assertions, since they're contractual constraints. Others should be propogated to the caller, but weren't. Now they are.
1 parent ec70f3a commit e7db8ce

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

vstring.h

+22-12
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,12 @@
2828
#ifndef VSTRING_H_
2929
#define VSTRING_H_
3030

31+
#include <assert.h>
3132
#include <stdbool.h>
3233
#include <stdint.h>
3334
#include <stdlib.h>
3435
#include <string.h>
36+
#include <errno.h>
3537
#include <math.h>
3638

3739
#ifndef vstring_inline
@@ -92,24 +94,22 @@ vs_init(vstring *vs, vstring_malloc *vm, enum vstring_type type, char *buf,
9294
memset(vs, 0, sizeof (*vs));
9395
} else {
9496
vs = calloc(1, sizeof (*vs));
97+
if (vs == NULL) {
98+
return NULL;
99+
}
95100
}
96101
vs->flags |= VS_NEEDSFREE;
97102
} else {
98103
memset(vs, 0, sizeof (*vs));
99104
}
100105

101-
if (vs == NULL) {
102-
return NULL;
103-
}
104-
105106
if (buf != NULL && size > 0) {
106107
vs->contents = buf;
107108
vs->size = size;
108109
}
109110
} else if ((type & VS_TYPE_STATIC) || (type & VS_TYPE_GROWABLE)) {
110-
if (buf == NULL || size == 0) {
111-
return NULL;
112-
}
111+
assert(buf != NULL);
112+
assert(size > 0);
113113

114114
if (vs == NULL) {
115115
if (vm != NULL) {
@@ -120,6 +120,9 @@ vs_init(vstring *vs, vstring_malloc *vm, enum vstring_type type, char *buf,
120120
memset(vs, 0, sizeof (*vs));
121121
} else {
122122
vs = calloc(1, sizeof (*vs));
123+
if (vs == NULL) {
124+
return NULL;
125+
}
123126
}
124127
vs->flags |= VS_NEEDSFREE;
125128
} else {
@@ -190,6 +193,9 @@ vs_resize(vstring *vs, size_t hint)
190193
} else {
191194
vs->contents = calloc(1, vs->size);
192195
}
196+
if (vs->contents == NULL) {
197+
return NULL;
198+
}
193199
} else {
194200
size_t size = vs->size * 2;
195201
if (size < hint) {
@@ -205,6 +211,9 @@ vs_resize(vstring *vs, size_t hint)
205211
} else {
206212
tmp = calloc(1, size);
207213
}
214+
if (tmp == NULL) {
215+
return NULL;
216+
}
208217

209218
memcpy(tmp, vs->contents, vs->size);
210219
vs->contents = tmp;
@@ -215,12 +224,12 @@ vs_resize(vstring *vs, size_t hint)
215224
} else {
216225
tmp = realloc(vs->contents, size);
217226
}
218-
if (tmp != NULL) {
219-
vs->contents = tmp;
220-
vs->size = size;
221-
} else {
227+
if (tmp == NULL) {
222228
return NULL;
223229
}
230+
231+
vs->contents = tmp;
232+
vs->size = size;
224233
} else if ((vs->type & VS_TYPE_STATIC)) {
225234
/*
226235
* VS_TYPE_STATIC strings that do not also have
@@ -251,8 +260,9 @@ vs_push(vstring *vs, char c)
251260
static vstring_inline bool
252261
vs_pushstr(vstring *vs, const char *s, uint64_t len)
253262
{
263+
assert(s != NULL);
254264

255-
if (s == NULL || len == 0) {
265+
if (len == 0) {
256266
return false;
257267
}
258268

0 commit comments

Comments
 (0)