links

lynx-like text mode web browser
git clone anongit@rnpnr.xyz:links.git
Log | Files | Refs | Feed | README | LICENSE

Commit: b84812e4cafd19721fe3ff403d71568f12147903
Parent: 19493ba36999593344b5aa4c393fb2047e1f966b
Author: Randy Palamar
Date:   Mon, 28 Nov 2022 23:27:15 -0700

string.c: rewrite add_bytes_to_str to use reallocarray

the function still needs to be modified to return the amount of bytes
added to the str rather than nothing.

Diffstat:
Mlinks.h | 1+
Mmain.c | 11+++++++++++
Mstring.c | 33++++++++-------------------------
3 files changed, 20 insertions(+), 25 deletions(-)

diff --git a/links.h b/links.h @@ -93,6 +93,7 @@ void die(const char *, ...); void usage(void); void *xmalloc(size_t); void *xrealloc(void *, size_t); +void *xreallocarray(void *, size_t, size_t); #define internal die #define error die #define fatal_exit die diff --git a/main.c b/main.c @@ -68,6 +68,17 @@ xrealloc(void *p, size_t len) return p; } +void * +xreallocarray(void *o, size_t n, size_t s) +{ + void *p; + + if (!(p = reallocarray(o, n, s))) + die("reallocarray: %s\n", strerror(errno)); + + return p; +} + static void sig_intr(void *t_) { diff --git a/string.c b/string.c @@ -97,36 +97,19 @@ extend_str(unsigned char **s, int n) void add_bytes_to_str(unsigned char **s, int *l, unsigned char *a, size_t ll) { - unsigned char *p; - size_t old_length; - size_t new_length; - size_t x; + unsigned char *p = *s; + size_t ol = *l; if (!ll) return; - p = *s; - old_length = (unsigned)*l; - if (ll + old_length >= (unsigned)INT_MAX / 2 || ll + old_length < ll) - overalloc(); - new_length = old_length + ll; - *l = (int)new_length; - x = old_length ^ new_length; - if (x >= old_length) { - /* Need to realloc */ - { - new_length |= new_length >> 1; - new_length |= new_length >> 2; - new_length |= new_length >> 4; - new_length |= new_length >> 8; - new_length |= new_length >> 16; - new_length++; - } - p = xrealloc(p, new_length); - *s = p; - } + *l = *l + ll; + + p = xreallocarray(p, *l, sizeof(unsigned char)); p[*l] = 0; - memcpy(p + old_length, a, ll); + memcpy(p + ol, a, ll); + + *s = p; } void