Merge pull request #463 from OpenWaterAnalytics/lrossman-dev

Refactored xstrcpy function
This commit is contained in:
Lew Rossman
2019-04-20 21:38:01 -04:00
committed by GitHub

View File

@@ -7,7 +7,7 @@
Authors: see AUTHORS
Copyright: see AUTHORS
License: see LICENSE
Last Updated: 04/18/2019
Last Updated: 04/20/2019
******************************************************************************
*/
@@ -805,7 +805,7 @@ void adjustpatterns(Network *network, int index)
Psource source;
// Adjust patterns used by junctions
for (j = 1; j <= network->Njuncs; j++)
for (j = 1; j <= network->Nnodes; j++)
{
// Adjust demand patterns
for (demand = network->Node[j].D; demand != NULL; demand = demand->next)
@@ -1039,33 +1039,37 @@ char *xstrcpy(char **s1, const char *s2, const size_t n)
// n = maximum size of strings
// Output: none
// Purpose: like strcpy except for dynamic strings.
// Note: The calling program is responsible for ensuring that
// s1 points to a valid memory location or is NULL. E.g.,
// the following code will likely cause a segment fault:
// char *s;
// s = xstrcpy(s, "Some text");
// while this would work correctly:
// char *s = NULL;
// s = xstrcpy(s, "Some text");
//----------------------------------------------------------------
{
size_t n1 = 0, n2;
size_t n1 = 0, n2 = 0;
// Find size of source string
if (s2) n2 = strlen(s2);
if (n2 > n) n2 = n;
// Source string is empty -- free destination string
if (s2 == NULL || strlen(s2) == 0)
if (n2 == 0)
{
free(*s1);
*s1 = NULL;
return NULL;
}
// Source string not empty -- overwrite destination string
else
{
// See if size of destination string needs to grow
if (*s1) n1 = strlen(*s1);
if ((n2 = strlen(s2)) > n) n2 = n;
if (n2 > n1)
{
free(*s1);
*s1 = (char *)malloc((n2 + 1) * sizeof(char));
}
if (n2 > n1) *s1 = realloc(*s1, (n2 + 1) * sizeof(char));
// Copy the new comment string into the existing one
if (*s1) strcpy(*s1, s2);
// Copy the source string into the destination string
strcpy(*s1, s2);
return *s1;
}
}
int strcomp(const char *s1, const char *s2)