Pointer arithmetic question.

B

Ben Bacarisse

S R said:
[snip]
     char *r = 0;
     while (*s++ || !r && (r = s - 1) || (*r++ = *t++));
^^^^^
I think there is a problem with the above. Once we reach the end of
string s, s is not guaranteed to point to a location containing 0 as
its value, assuming s as being sent in by the caller of the function
(in your earlier examples you made ",*s =0" which was the correct).
The concatenation happens through r but the check *s++ is problematic,
isn't it?

Yes, you're right. I don't know how that got through the test cases
because I had one to cover that situation -- I had the same bug in the
previous version until I added this test case.

There's another bug as well. Because the middle condition is true but
copies no characters, s is incremented once more it needs to be. We have
to assume that s points somewhere big enough for the concatenated string
so incrementing s along with r is safe provided we don't go too far. If
the target is only just big enough, s will be incremented beyond the
specially permitted "one past the end" position.

Oh well... I don't think I'll offer a fix since the "challenge" of
cramming it all in the condition seems a bit old now.
 
P

Prathamesh Kulkarni

An attempt for one-line condition for strcat.

char *mystrcat(char *s, char *t)
{
char *r = 0, *temp = s;

while ((*s && s++) || (r == 0 && (r = s) || (*r++ = *t++)))
;
return temp;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top