strcat implementation

2019-02-03 18:45发布

I tried to implement the strcat by myself, and I found the strcat implementation from Wiki like this......but when I use it, there is segmentation fault.

What's wrong with the code below?

char *
strcat(char *dest, const char *src)
{
    size_t i,j;
    for (i = 0; dest[i] != '\0'; i++)
        ;
    for (j = 0; src[j] != '\0'; j++)
        dest[i+j] = src[j];
    dest[i+j] = '\0';
    return dest;
}

标签: c strcat
5条回答
戒情不戒烟
2楼-- · 2019-02-03 18:54

I would strongly suggest using pointers rather than integer indexes, for fear of integer overflow. Even if size_t is the same number of bits as char *, you're adding indices where you wouldn't be adding pointers.

I guess that's more or less academical; if you're calling strcat() on multi-gigabyte strings you're probably in all sorts of trouble.

Here's a pointer-based version, for completeness' sake:

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

Sure, this does take another pointer's worth of space for the rdest return value, but I think that's a fine trade-off.

Also note that you can't legally define a function called strcat() in ordinary application code; that whole namespace (public functions with names starting with str) is reserved for the implementation.

查看更多
Animai°情兽
3楼-- · 2019-02-03 18:58

Its working fine with me, I have check it.

    #include "stdio.h"


    char *strcat(char *dest, const char *src)

    {

    size_t i,j;

    for (i = 0; dest[i] != '\0'; i++)

        ;

    for (j = 0; src[j] != '\0'; j++)

        dest[i+j] = src[j];

    dest[i+j] = '\0';

    return dest;

}


void main(void)

{

    char a[10]={"abc"}, b[10]={"def"};

    strcat(a,b);

    printf("%s",a);

    getchar();

}
查看更多
我想做一个坏孩纸
4楼-- · 2019-02-03 18:59

Allocate enough memory for the destination string.. ie atleast (length of source string + 1).

查看更多
Emotional °昔
5楼-- · 2019-02-03 19:16

dest needs to have enough memory to accommodate the concatenation in this implementation. In this implementation, it would have to be allocated by the caller. You should also be sure both dest and src are null terminated. If dest does not have enough memory, this will overwrite memory that could be used by something else.

查看更多
我想做一个坏孩纸
6楼-- · 2019-02-03 19:18

the code is okay.

Looks like you have a problem in the calling code.

Did you remember to allocate enough memory for the target string?

查看更多
登录 后发表回答