Folks, I have been told that there is one logical problem with this code. Basically, this is an implementation of the library function strcat().

The intended beahviour of this function to concatenate ct to the end of s. Return s.

I could not find any logical problems with the code, apart from the fact that the final string should be NULL terminated, but I am not sure that can be classified as an error.

Could you help me find the error, if there is any.

char *strcat(char *s, const char *ct)
{
int i, start;
start = strlen(s);
for (i = 0; i < strlen(ct); i++)
{
s[start + i] = ct[i];
}
return s;
}

P.S. -
Is this the only correction needed in the code:

s[start+i]='\0'; \\after the loop

>I could not find any logical problems with the code...
There is an obvious problem: this code does not copy zero byte of ct so the result string is not terminated (i.e. is not C-string).
That's solution:

int ctsz = strlen(ct)+1; // don't use strlen() in for condition!
for (i = 0; i < ctsz; i++)
   ...

or more safe and effective:

char* strcat(char* t, const char* s)
{
    if (s)
    if (char* p = t) {
        while (*p)  p++;
        while ((*p++ = *s++) != '\0') ;
    }
    return t;
}

Sorry, it was C++, that's C:

...
char* p = t;
if (s && t) {
    while (*p) ... the same as above

the fact that it doesnt terminate the string with a NULL is the error.

a string must have a NULL termination, or else it's just a character array.

Sorry, there was C++ code in my previous post (and I can't edit my posts - don't know why).
That's C code:

char* p = t;
if (t && s) {
   while (... /* the same as C++ code */

the fact that it doesnt terminate the string with a NULL is the error.

a string must have a NULL termination, or else it's just a character array.

Please, don't forget: NULL is a ponter value in C. You (and me) can't terminate the string with a pointer ;)

Comments
ok, you got me :)

um... i'm not sure get it. is this some kind of semantic trickery? are we fixating on my use of capital letters or something?

because C-strings are most certainly terminated by null characters. and if it's not done by a standard library, then WE will be responsible for terminating it ourselves.

http://en.wikipedia.org/wiki/Null_character

oh, that.... i guess i forgot about this particular epic battle :P

well i was just emphasizing the fact that it's a null character, ant that he needs to terminate the string

but okay. i concede the point. because several libraries define capital NULL, i should be more precise, and refer to the terminating character as '\0'

.

> guess i forgot about this particular epic battle...
It's not the echo of the epic battle, it's a regular untidiness ;)
See the language standard, for example: ...null character term used...
In addition the C has a case-sensitive syntax ;)

Comments
ok :)
This article has been dead for over six months. Start a new discussion instead.