From 3e53a79ea9825172f8a5ccc019af088c5a1e0994 Mon Sep 17 00:00:00 2001 From: Kaz Kylheku Date: Sun, 6 Oct 2024 13:27:10 -0700 Subject: bugfix: memory corruption due to sizeof (dstr) This was reportd by Jeremy Brubaker along with a working patch. I reworked it to a shorter fix. Jeremy is using GCC 13.3.1, Evidently, the sizeof a struct which has a flexible array member is not the same as the offsetof that member, which we are relying on. I have to research more into this because ISO C seems to require them to be the same. * pw.c (dstr_of, dsgrow): use offsetof (struct dsr, str) rather than sizeof (dstr) when displacing the string pointer back to the header, and when allocating the space. --- pw.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pw.c b/pw.c index 29b4cb5..a2ddff0 100644 --- a/pw.c +++ b/pw.c @@ -26,6 +26,7 @@ // POSSIBILITY OF SUCH DAMAGE. #include +#include #include #include #include @@ -130,7 +131,7 @@ typedef struct dstr { char str[]; } dstr; -#define dstr_of(str) ((dstr *) ((str) - sizeof (dstr))) +#define dstr_of(s) ((dstr *) ((s) - offsetof (struct dstr, str))) static char *pw_name; static int poll_interval = 1000; @@ -203,7 +204,7 @@ static char *dsgrow(char *str, size_t len) { dstr *ds = str ? dstr_of(str) : 0; int flags = str ? ds->flags : 0; - size_t size = sizeof *ds + len + 1; + size_t size = offsetof(struct dstr, str) + len + 1; assert (ds == 0 || ds->refs == 1); -- cgit v1.2.3