From 3fedf2e388842e75bbef4d9cc36e0e414f79f2f1 Mon Sep 17 00:00:00 2001 From: Sami Kerola Date: Mon, 29 Aug 2016 18:55:54 +0100 Subject: [PATCH] reliability: always check strdup() return value Exit if allocation fails. --- asn.c | 4 ++-- dns.c | 2 +- mtr.c | 2 +- utils.c | 12 ++++++++++++ utils.h | 1 + 5 files changed, 17 insertions(+), 4 deletions(-) diff --git a/asn.c b/asn.c index d31524b..6bc2f17 100644 --- a/asn.c +++ b/asn.c @@ -90,7 +90,7 @@ static char *ipinfo_lookup(const char *domain) { if((len = res_query(domain, C_IN, T_TXT, answer, PACKETSZ)) < 0) { if (iihash) DEB_syslog(LOG_INFO, "Malloc-txt: %s", UNKN); - return (iihash)?strdup(UNKN):UNKN; + return (iihash) ? xstrdup(UNKN) : UNKN; } pt = answer + sizeof(HEADER); @@ -251,7 +251,7 @@ static char *get_ipinfo(struct mtr_ctl *ctl, ip_t *addr){ if ((val = split_txtrec(ctl, ipinfo_lookup(lookup_key)))) { DEB_syslog(LOG_INFO, "Looked up: %s", key); if (iihash) - if ((item.key = strdup(key))) { + if ((item.key = xstrdup(key))) { item.data = items; hsearch(item, ENTER); DEB_syslog(LOG_INFO, "Insert into hash: %s", key); diff --git a/dns.c b/dns.c index 6148b0b..ab6324a 100644 --- a/dns.c +++ b/dns.c @@ -239,7 +239,7 @@ extern void dns_ack(struct mtr_ctl *ctl) longipstr (host, &hostip, ctl->af); r = findip (ctl, &hostip); if (r) - r->name = strdup (name); + r->name = xstrdup (name); else error (0, 0, "dns_ack: Couldn't find host %s", host); } diff --git a/mtr.c b/mtr.c index 99f4cb0..14502e3 100644 --- a/mtr.c +++ b/mtr.c @@ -154,7 +154,7 @@ append_to_names(const char* item) { if (name == NULL) { error(EXIT_FAILURE, errno, "memory allocation failure"); } - name->name = strdup(item); + name->name = xstrdup(item); name->next = names; names = name; } diff --git a/utils.c b/utils.c index 2ba3654..f6c4326 100644 --- a/utils.c +++ b/utils.c @@ -97,3 +97,15 @@ extern void *xmalloc(const size_t size) error(EXIT_FAILURE, errno, "cannot allocate %zu bytes", size); return ret; } + +extern char *xstrdup(const char *str) +{ + char *ret; + + if (!str) + return NULL; + ret = strdup(str); + if (!ret) + error(EXIT_FAILURE, errno, "cannot duplicate string: %s", str); + return ret; +} diff --git a/utils.h b/utils.h index db3c0dd..5f9609d 100644 --- a/utils.h +++ b/utils.h @@ -34,3 +34,4 @@ static inline void xstrncpy(char *dest, const char *src, size_t n) } extern void *xmalloc(const size_t size); +extern char *xstrdup(const char *str); -- 2.47.2