简体   繁体   中英

What's wrong with printf in my strcat code?

I have made this program to emulate strcat functionality but there is an error with printf which I don't understand...

Here is the code:

#include <stdio.h>

char *mystrcat(char *s1, char *s2);

int main(void)
{
    char *s1,*s2;
    s1="asdad";
    s2="asdad";
    s1=mystrcat(s1,s2);
    printf(s1);

    return 0;
}
char *mystrcat(char *s1,char *s2)
{
    int i,j;
    for(i=0;s1[i]<'\0';i++) ;
    for(j=0;s2[j]!='\0';j++) s1[i+j]=s2[j];
    s1[i+j]='\0';
    return s1;
}

至少s1[i] < '\\0's1[i] < 0 ,始终为假。

The first problem is that s1 doesn't have enough space to append s2 to it. You need the size of the buffer pointed to by s1 to be at least strlen(s1) + strlen(s2) + 1 (the + 1 being the NUL terminator).

The second problem is that string literals are read-only. You assign s1 from "asdad" , which creates a pointer to (potentially) read-only memory. Of course the first problem means that you wouldn't have enough space to append to the end even if it were writeable, but this is one of the common pitfalls in C and worth mentioning.

Third problem (already mentioned in another answer ) is that the comparison s1[i] < '\\0' is wrong and you will not correctly find the length of s1 since the loop will not run even a single iteration. The correct condition is the same as in your second loop, != '\\0' . (This masks problem 1 since then you are inadvertently overwriting s1 from the beginning.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM