bore

Unnamed repository
Log | Files | Refs | README

commit f473a4b7060fbdcf38617067851e855acef9d5e9
parent 8321dcb85b19a84bdf1940148dae734c90602753
Author: phoebos <ben@bvnf.space>
Date:   Thu, 23 Sep 2021 20:29:42 +0100

ed: fix insert_line_before

the layout of struct line meant that when new->len was written, it would overwrite the ends of new->s.
for it to work with line.s declared as s[1], it would have to be at the end and then the first malloc
would allow enough space at the end of the struct for the string.

Now, the string is properly malloc'd so it has enough space wherever it is in the struct.
A bug in malloc'ing first the wrong size caused all kinds of problems!

Diffstat:
Med.c | 14+++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/ed.c b/ed.c @@ -17,9 +17,9 @@ int buf_size = BUFSIZ; int buf_used = 0; struct line { - char s[1]; int len; struct line *prev, *next; + char *s; }; struct line *first; @@ -47,14 +47,22 @@ find_line(int num) { struct line * insert_line_before(char *s, int len, int num) { struct line *old, *new; - new = malloc(sizeof(struct line) + len); + new = malloc(sizeof *new); if (new == NULL) { fprintf(stderr, "ed: malloc: %s\n", strerror(errno)); return NULL; } old = find_line(num); + new->s = malloc(len + 1); + if (new->s == NULL) { + free(new); + fprintf(stderr, "ed: malloc: %s\n", strerror(errno)); + return NULL; + } memcpy(new->s, s, len); + new->s[len] = '\0'; + new->len = len; new->prev = old->prev; new->next = old; @@ -244,7 +252,7 @@ main(int argc, char **argv) { return 1; } buf = buf_start; - first = malloc(sizeof(first)); + first = malloc(sizeof(*first)); if (first == NULL) { fprintf(stderr, "ed: malloc: %s\n", strerror(errno)); return 1;