Error while writing strcat() using pointers

∥☆過路亽.° 提交于 2020-01-11 07:27:14

问题


I am trying to learn C with The C programming Language by K&R. I am trying to write a the strcat() program using pointers.

char *strcat (char *s, char *t){
    char *d;
    d = s;
    while(*s++);
    s--;
    while(*s++ = *t++);
    return d;
}

int main () {
    char *name1;
    char *name2;
    name1 = "stack" ;
    name2 = "overflow";
    printf("%s %s\n", name1, name2);
    printf("strcat out : %s", strcat(name1, name2));
    return 0;
}

But I am getting the ouput as

stack overflow
Segmentation fault

Why is it not working ? Can anybody clarify the mistake here..


回答1:


Because the pointers are pointers to literals, and not only are those read only the destination is not big enough to contain both the strings. For at least string1 you would want to use an array of at least big enough size to contain both strings (including the terminator). Like:

char string1[128] = "Stack";

or

char string1[128];
strcpy(string1, "Stack");



回答2:


The program tries to append characters to the literal string "stack". Don't do that; create an array of characters that's large enough to hold the result, copy the first string into the array, and then strcat the rest of the string.

Oh, and name your function something other than strcat. That name is already taken.




回答3:


In this line:

while(*s++ = *t++);

you dereference s which points to one-past-the-end of the char array "stack". This causes segmentation fault error.




回答4:


 char *name1;
 char *name2;
 name1 = "stack" ;
 name2 = "overflow";

==>

 char name1[20];
 char name2[10];
 memcpy(name1,"stack") ;
 memcpy(name2,"overflow");


来源:https://stackoverflow.com/questions/18549904/error-while-writing-strcat-using-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!