fix null pointer subtraction and comparison in stdio
[musl.git] / src / stdio / getdelim.c
blobc313775d3d026f11a9660e21b888959ea35f680a
1 #include "stdio_impl.h"
2 #include <string.h>
3 #include <stdlib.h>
4 #include <inttypes.h>
5 #include <errno.h>
7 ssize_t getdelim(char **restrict s, size_t *restrict n, int delim, FILE *restrict f)
9 char *tmp;
10 unsigned char *z;
11 size_t k;
12 size_t i=0;
13 int c;
15 FLOCK(f);
17 if (!n || !s) {
18 f->mode |= f->mode-1;
19 f->flags |= F_ERR;
20 FUNLOCK(f);
21 errno = EINVAL;
22 return -1;
25 if (!*s) *n=0;
27 for (;;) {
28 if (f->rpos != f->rend) {
29 z = memchr(f->rpos, delim, f->rend - f->rpos);
30 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
31 } else {
32 z = 0;
33 k = 0;
35 if (i+k+1 >= *n) {
36 if (k >= SIZE_MAX/2-i) goto oom;
37 size_t m = i+k+2;
38 if (!z && m < SIZE_MAX/4) m += m/2;
39 tmp = realloc(*s, m);
40 if (!tmp) {
41 m = i+k+2;
42 tmp = realloc(*s, m);
43 if (!tmp) goto oom;
45 *s = tmp;
46 *n = m;
48 memcpy(*s+i, f->rpos, k);
49 f->rpos += k;
50 i += k;
51 if (z) break;
52 if ((c = getc_unlocked(f)) == EOF) {
53 if (!i || !feof(f)) {
54 FUNLOCK(f);
55 return -1;
57 break;
59 if (((*s)[i++] = c) == delim) break;
61 (*s)[i] = 0;
63 FUNLOCK(f);
65 return i;
66 oom:
67 f->mode |= f->mode-1;
68 f->flags |= F_ERR;
69 FUNLOCK(f);
70 errno = ENOMEM;
71 return -1;
74 weak_alias(getdelim, __getdelim);