From 8ed7080227c1a908f52952f3c85916b9d7f6a59b Mon Sep 17 00:00:00 2001 From: Jim Monte Date: Sat, 15 Jun 2019 11:10:23 +0200 Subject: [PATCH] [PATCH #70] Made parameter const and reduced excess allocation. --- src/frontend/quote.c | 47 +++++++++++++++++++++------------- src/include/ngspice/cpextern.h | 2 +- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/frontend/quote.c b/src/frontend/quote.c index cb62a19a6..3403d1e96 100644 --- a/src/frontend/quote.c +++ b/src/frontend/quote.c @@ -10,6 +10,8 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group * your IBM machine and buy a vax. */ +#include + #include "ngspice/ngspice.h" #include "ngspice/cpdefs.h" #include "quote.h" @@ -70,27 +72,36 @@ cp_striplist(wordlist *wlist) } -/* Remove the "" from a string. */ +/* Create a copy of the input string removing the enclosing quotes, + * if they are present */ char * -cp_unquote(char *string) +cp_unquote(const char *p_src) { - char *s; - size_t l; - - if (string) { - l = strlen(string); - s = TMALLOC(char, l + 1); + if (!p_src) { /* case of no string */ + return (char *) NULL; + } - if (l >= 2 && *string == '"' && string[l-1] == '"') { - strncpy(s, string+1, l-2); - s[l-2] = '\0'; - } else { - strcpy(s, string); - } + const size_t len_src = strlen(p_src); /* input str length */ + size_t len_dst; - return (s); - } else { - return NULL; + /* If enclosed in quotes locate the source after the quote and + * make the destination length 2 chars less */ + if (len_src >= 2 && *p_src == '"' && p_src[len_src - 1] == '"') { + len_dst = len_src - 2; + ++p_src; /* step past first quote */ } -} + else { /* not enclosed in quotes */ + len_dst = len_src; + } + + /* Allocate string being returned and fill. */ + char * const p_dst = TMALLOC(char, len_dst + 1); + strncpy(p_dst, p_src, len_dst); + p_dst[len_dst] = '\0'; + + return p_dst; +} /* end of function cp_unquote */ + + + diff --git a/src/include/ngspice/cpextern.h b/src/include/ngspice/cpextern.h index fd079bb84..31c341c79 100644 --- a/src/include/ngspice/cpextern.h +++ b/src/include/ngspice/cpextern.h @@ -133,7 +133,7 @@ extern void out_send(char *string); /* quote.c */ -extern char *cp_unquote(char *string); +extern char *cp_unquote(const char *string); extern void cp_quoteword(char *str); extern void cp_striplist(wordlist *wlist); extern void cp_wstrip(char *str);