[given an array of "char" that does not have a terminating '\0', i.e.,
is not a C string...]
Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)
(since str is an array of chars without the teminating \0)?
As several others have said, yes, all three of these calls look for
the terminating '\0', which -- since there is none in the array --
triggers undefined behavior. The first call is fixable, however:
since we know that "str" -- not such a good name, as it is not a
C string -- ends after 12 "char"s, we can use:
printf("%.12s", str);
or (because it is an array, so that sizeof works):
printf("%.*s", (int)sizeof str, str);
(Note that this second call would not work if str were a pointer
pointing to this not-a-C-string 12-character array, rather than
the actual array name itself. In that case, you would get
sizeof(char *) instead of sizeof(char [12]).)
All of this means that if printf() is implemented in C, its "%s"
handler must not use strlen() if a precision has been specified.
I noticed and fixed this bug in the printf() that Keith Bostic and
I coded up for 4.4BSD. We ended up with code of the form:
case 's':
s = va_arg(ap, char *);
if (flags & PREC) { /* e.g., %.10s, %.*s */
p = memchr(s, '\0', precision);
len = p ? p - s : precision;
} else
len = strlen(s);
/*
* then output no more than 'len' bytes from the area
* pointed to by 's', obeying field-width and left- and
* right-adjustment and so on, so that, e.g., %-100.10s
* and %30s work correctly.
*/
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to