char *_str_dup(const char *str, const char *file, const char *function, int line)
{
if(IS_NULLSTR(str))
{
log_string(Format("_str_dup: %s:%s:%d called with NULL values!", file, function, line ) );
return NULL;
}
return strdup(str); // relay to our actual strdup!
}
#define str_dup(str) _str_dup(str, __FILE__, __FUNCTION__, __LINE__)
char *replace_name_tokens(const char *str, const char *first_name, const char *last_name)
{
char *result = NULL;
char *match = NULL;
char *current = NULL;
if(!str || !*str)
return str;
if(!(match = strchr(str, (int)'$')))
return str;
// The tokens recognized are $f for first name, and $l for last name.
// The original function also replace $$ with $, and "$ " with $.
current = str;
while(match = strchr(current, (int)'$')) {
if(!result) {
result = strndup(current, (match - current));
} else {
result = realloc(result, strlen(result) + (match - current + 1) * sizeof(char));
strncat(result, current, match - current);
}
current = match + 1;
switch(*current) {
case '\0':
// A $ at the end of the string is a false match.
break;
case 'f':
result = realloc(result, (strlen(result) + strlen(first) + 1) * sizeof(char));
strcat(result, first);
break;
case 'l':
result = realloc(result, (strlen(result) + strlen(last) + 1) * sizeof(char));
strcat(result, last);
break;
case '$':
result = realloc(result, (strlen(result) + 2) * sizeof(char));
strcat(result, "$");
break;
case ' ':
// Should this really be a $ ???
result = realloc(result, (strlen(result) + 2) * sizeof(char));
strcat(result, "$");
break;
default:
// Copy it verbatum.
result = realloc(result, (strlen(result) + 3) * sizeof(char));
strncat(result, match, 2);
break;
}
current++;
}
leftover = strlen(current);
if(leftover > 0) {
result = realloc(result, (strlen(result) + leftover + 1) * sizeof(char));
strcat(result, current);
}
return result;
}
(int)'$'
. +-+-+-+-+-+-+-+-+-+
. | | | | | | | | | |
. +-+-+-+-+-+-+-+-+-+
. ^ ^
. | |
. X Y
I know there is a memory leak in this code (str) and I thought adding a free to it would take care of it, but then it crashes when I go to startup saying there is an invalid pointer. What am I doing wrong?