String concatenation without strcat in C

前端 未结 7 819
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 13:44

I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include
#include
#include<         


        
7条回答
  •  误落风尘
    2021-01-13 14:26

    You cannot safely write into those arrays, since you have not made sure that enough space is available. If you use malloc() to allocate space, you can't then overwrite the pointer by assigning to string literal. You need to use strcpy() to copy a string into the newly allocated buffers, in that case.

    Also, the length of a string in C is computed by the strlen() function, not length() that you're using.

    When concatenating, you need to terminate at the proper location, which your code doesn't seem to be doing.

    Here's how I would re-implement strcat(), if needed for some reason:

    char * my_strcat(char *out, const char *in)
    {
      char *anchor = out;
      size_t olen;
    
      if(out == NULL || in == NULL)
        return NULL;
    
      olen = strlen(out);
      out += olen;
      while(*out++ = *in++)
        ;
      return anchor;
    }
    

    Note that this is just as bad as strcat() when it comes to buffer overruns, since it doesn't support limiting the space used in the output, it just assumes that there is enough space available.

提交回复
热议问题