D
Dan Pop
In said:This can be trivially avoided by using sprintf instead of strcat
Errm, what?
Say you have...
List *scan = NULL;
char buf[4096]; /* we "know" this is long enough */
buf[0] = 0;
scan = beg;
while (scan)
{
strcat(buf, scan->data);
scan = scan->next;
}
...how does sprintf() help? Ok, so you can do something like...
ptr = buf;
while (scan)
{
ptr += sprintf(ptr, "%s", scan->data); /* assume sprintf() has an ISO
* return value*/
We normally assume that standard library functions return what the
standard says they do. Without this assumption, the standard library
becomes (next to) useless.
scan = scan->next;
}
...but then you might as well just do...
ptr = buf;
while (scan)
{
size_t len = strlen(scan->data);
memcpy(ptr, scan->data, len);
ptr += len;
scan = scan->next;
}
Except that it requires more code and is, therefore, less readable and
that it requires one more statement, after the loop, to properly terminate
the string.
...and after you do that more than once you realize that you want...
char *my_stpcpy(char *dst, const char *src)
You can simply name it stpcpy(), especially since this is the name you
use below
{
size_t len = strlen(src);
memcpy(dst, src, len);
dst += len;
return (dst);
}
ptr = buf;
while (scan)
{
ptr = stpcpy(ptr, scan->data);
scan = scan->next;
}
...at which point you've just _reinvented the wheel_ for about the
millionth time, creating your own clumsy string API.
Which is pointless, considering that the sprintf-based solution achieves
the same thing, with the same source code complexity, while staying with
the standard API.
All because the c
library string APIs are deficient ... which is pretty much what was
argued.
The only defficiency I can see is that strcpy and strcat (and friends)
have a (mostly) useless return value. For the rare cases when this is
a problem, sprintf provides a solution without needing to reinvent
anything and without having to take the overhead of repetitive strcat()
calls (sprintf has its own overhead, but it is constant per call).
Dan