简体   繁体   中英

What is Wrong with My Concatenation Operation?

I was trying to implement strcat() , so I came up with this code. But, I don't know what is wrong with it? It's giving me segmentation fault.

I was thinking that this might be a memory allocation mess? Is that it? How can I fix it without using malloc() ?

#include <stdio.h>

char *strcat(char *s,char *d){

 while(*s++ != '\0') ;
 while(*s++ = *d++) ;

 *s = '\0';

 return s;
}

int main(){

char s[20]= "source";
char d[20]= "dest";

printf("%s\n",strcat(s,d));

return 0;
}

I have to concat d ahead of s .

  1. The strings are in read only memory
  2. The string s will not be long enough

To fix:

   ...
   #define S_STR "source"

   char *d= "dest";
   char *s= S_STR;
   s = malloc(strlen(s) + strlen(d) + 1);
   strcpy(s, S_STR);
   printf("%s\n",strcat(s,d));
   free(s);
   return 0;
}

The s, d are string constants! You should never do such things. have a big array like char s[100], copy source to it, and then use your concatenation. Remember that s should have room to accomodate the content of d!

i fixed it

#include <stdio.h>
#define SIZE 20

char *strocat(char *s,char *d){

 char *temp = s;

 while(*s++ != '\0');
 *--s;
 while(*s++ = *d++);

 *s = '\0';

 return temp;
}

int main(){

char s[SIZE] = "source";
char d[SIZE] = "dest";

printf("%s\n",strocat(s,d));

return 0;
}

The strings s and d you declared are constant string literals,You can't modify them. you should declare two char arrays and make sure the one you are copying to is big enough to hold the other.

#include <stdio.h>

char *strcat(char *s,char *d)
{
    //Get length of s string
    size_t len = strlen(s);

    //declare new pointer and assign it the value of s
    char *ptr = s;

    //move the pointer to the end of the string
    ptr += len;

    //copy contentes of d string to s string
    while( *d != '\0' )
    {
        *ptr++ = *d++;
    }

    *ptr = '\0';

    //return s
    return s;
}

int main()
{
    //make sure s array length is big enough to accomodate d string
    char s[50] = "source";

    char d[] = "dest";

    printf("%s\n",strcat(s,d));

    return 0;
}

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