Re: String interpolation



david.chanters@xxxxxxxxxxxxxx wrote:
Hi all,

I am sure this is going to be another of me "close, keep trying, no
cigar" type questions -- as with all my others I have learnt tons, so
I will say thanks in advance. :)

I'm trying to do some string interpolation -- that is, expand certain
placeholders for other values, much like sprintf() does. Here's an
example:

static char* expand(const char *format)
{
char string[4096];
char *toReturn;

while (*format)
{
fprintf(stderr, "Looking at: %s\n", format);
int pos;

/* Until we find a % character. */
for (pos = 0; format[pos] && format[pos] != '%'; pos++);

/* Copy everything up to this into string. */
strncat(string, format, pos);

Danger, Will Robinson! The first time you get here, nothing
has ever been stored in any element of string[]. In particular,
strncat() may or may not be able to find a '\0' in it to mark the
end of "the string that's already there," and if it doesn't find
a '\0' there's no telling what might happen. (Whether you ever
get here a second time is open to question, because after the
first time you are well and truly Lost In Space.)

/* Advance where we're looking in format to that point. */
format += pos;

/* And try again if we have no percent character. */
if (*format != '%')
continue;

fprintf(stderr, "Before switch: %s\n", string);
format++;
switch (*format)
{
case 'n':
strcat(string, "Name");
break;
case 'c':
strcat(string, "County level address");
break;
case 'r':
strcat (string, "Restrictions");
break;
default:
break;
}

if (*format)
format++;
}
toReturn = string;
fprintf(stderr, "I am sending back: %s\n", toReturn);
return toReturn;

Danger, Will Robinson! You are returning a pointer to
the first character of string[], but string[] itself will cease
to exist when the function returns. The caller will therefore
receive a pointer that it cannot use for anything.

}

expand( "David (%n) --> Valued: [%c]" );

But as the debug via fprintf()s inside expand() shows, it seems to be
going beyonf (I assume) the NUL character -- since it reaches a point
of correctly exanding the string and keeps on going -- which isn't
right.

Although I'm not sure just what you mean by "going beyonf
the NUL character," my suspicion is that misbehavior inside the
function is most likely due to the first error mentioned above.
Misbehavior from the second would not manifest itself until
after the function returns.

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.