Hm. For whatever reason this ended up on cctech when I responded, so
here it is again on the right list (sorry for the spam if you're on both.)
On 10/15/2011 10:34 AM, Fred Cisin wrote:
>
mystery(char *s, char *t) {
> while(*s++ = *t++)
> ;
> }
On Fri, 14 Oct 2011, Josh Dersch wrote:
And I would tend to prefer a loop that involves
some sort of bounds
checking .
In C, what happens when you do:
char A[1000];
char * t;
char * s;
strcpy(A,"anything");
t =&A[0];
s =&A[1];
strcpy(t,s); /*to delete a character*/
printf("%s",A);
t =&A[1];
s =&A[0];
strcpy(t,s); /*to insert a character*/
printf("%s",A);
Depends on the compiler and the C-runtime, I suppose. All of the
documentation I have suggests that the behavior of strcpy is undefined
when the strings being copied overlap.
<pedantic>
Why?
How SHOULD you do it?
In C, if you want ANY error checking, then YOU have to put it in, thus
making it an inappropriate language for beginners to write operating
systems in.
</pedantic>
So no C runtime libraries do any error checking for you? That's not
true. I'm pretty sure fopen() won't return you a file handle pointing
into the ether (and scribbling all over the disk if the programmer
chooses to use it) if the user asked to open a file without checking to
see if it existed first.
I appreciate (and understand) the notion that for absolute performance,
automatic bounds checking of arrays can be an impediment. I also know
that all people make mistakes, no matter how hard they try and how long
they've been writing operating systems. (Anyone who says differently is
either lying or hasn't yet found their mistakes.) And these days, a
mistake in bounds checking costs many more people than the developer.
C-style strings and the library of runtime functions that support them
do not make anyone's lives easier in the correctness department, due to
issues inherent in the design (as has been mentioned by others on this
list). Where I work, strcpy (and their ilk) are verboten; we use
variants like strcpy_s to prevent inadvertent buffer overflows, since it
does the validation we'd have to do manually anyway and it's guaranteed
to work properly. And it's not like our code spends 99% of its time
copying strings, so the performance hit is approximately zero.
- Josh
--
Grumpy Ol' Fred cisin at
xenosoft.com