Fixed-size buffers in C (10)

1 Name: #!usr/bin/anon 2005-11-17 04:47 ID:kotEQ2Sk

I found an interesting discussion on the use of the bounds-checking strlcpy(), strlcat(), and snprintf() functions, versus their counterparts strcpy(), strcat(), and sprintf(), which assume a destination buffer of infinite size:

http://sources.redhat.com/ml/libc-alpha/2002-01/msg00001.html

Surprisingly to me, the glibc developers seem to believe that the bounds-checking functions should be avoided, because fixed-size buffers shouldn't be used. They believe that buffers should be dynamically allocated as necessary. In other words, I guess they write fun code like:

char *str;
str = malloc(strlen("//.log") + strlen(a) + strlen(b) + 11 + 1);
sprintf(str, "%s/%s/%d.log", a, b, n);

It seems to me that not only is this rarely needed (come on, how often is str going to need more than, say, 200 characters?), this sort of calculation is prone to error, and snprintf() should be used anyway for an extra layer of safety. I can say this with some experience, as I frequently used to mess up calculations like that, until finally I got some sense and started doing:

char str[200];
if (snprintf(str, sizeof str, "%s/%s/%d.log", a, b, n) >= sizeof str)
{
/* string was too long */
...
}

Is it just me, or is creating strings the first way absolutely crazy? Furthermore, even if strings are being created that way, isn't it criminally stupid not to use a bounds-checking function anyway, since essentially you are getting a little performance gain for betting that programmers can program perfectly?

Discuss!

This thread has been closed. You cannot post in this thread any longer.