Added epicsStrnDup() and dbmfStrndup() routines

The JSON parser passes string arguments with a length
instead or nil-terminating them. These routines make it
simple to copy such strings into either permanent or
temporary storage.
This commit is contained in:
Andrew Johnson
2016-09-03 13:25:19 -05:00
parent 23c71e9965
commit 6e88d48615
4 changed files with 23 additions and 4 deletions

View File

@@ -158,10 +158,18 @@ void* dbmfMalloc(size_t size)
char * dbmfStrdup(const char *str)
{
size_t len = strlen(str);
char *buf = dbmfMalloc(len + 1);
strcpy(buf, str);
return buf;
size_t len = strlen(str);
char *buf = dbmfMalloc(len + 1); /* FIXME Can return NULL */
return strcpy(buf, str);
}
char * dbmfStrndup(const char *str, size_t len)
{
char *buf = dbmfMalloc(len + 1); /* FIXME Can return NULL */
buf[len] = '\0';
return strncpy(buf, str, len);
}
void dbmfFree(void* mem)

View File

@@ -26,6 +26,7 @@ extern "C" {
epicsShareFunc int dbmfInit(size_t size, int chunkItems);
epicsShareFunc void * dbmfMalloc(size_t bytes);
epicsShareFunc char * dbmfStrdup(const char *str);
epicsShareFunc char * dbmfStrndup(const char *str, size_t len);
epicsShareFunc char * dbmfStrcat3(const char *lhs, const char *mid,
const char *rhs);
epicsShareFunc void dbmfFree(void *bytes);

View File

@@ -223,6 +223,15 @@ int epicsStrnCaseCmp(const char *s1, const char *s2, size_t len)
return 0;
}
char * epicsStrnDup(const char *s, size_t len)
{
char *buf = mallocMustSucceed(len + 1, "epicsStrnDup");
strncpy(buf, s, len);
buf[len] = '\0';
return buf;
}
char * epicsStrDup(const char *s)
{
return strcpy(mallocMustSucceed(strlen(s)+1, "epicsStrDup"), s);

View File

@@ -32,6 +32,7 @@ epicsShareFunc size_t epicsStrnEscapedFromRawSize(const char *buf, size_t len);
epicsShareFunc int epicsStrCaseCmp(const char *s1, const char *s2);
epicsShareFunc int epicsStrnCaseCmp(const char *s1, const char *s2, size_t len);
epicsShareFunc char * epicsStrDup(const char *s);
epicsShareFunc char * epicsStrnDup(const char *s, size_t len);
epicsShareFunc int epicsStrPrintEscaped(FILE *fp, const char *s, size_t n);
#define epicsStrSnPrintEscaped epicsStrnEscapedFromRaw
epicsShareFunc int epicsStrGlobMatch(const char *str, const char *pattern);