2

My goal is to recreate the strcat() function without libraries:

#include <stdio.h>

char    *ft_strcat(char *dest, char *src)
{
    int i;
    int j;

    i = 0;
    j = 0;
    while   (dest[i] != '\0')
    {
        i++;
    }
    while   (src[j] != '\0')
    {
        dest[i] += src[j];
        i++;
        j++;
    }
    return (dest);
}

int main()
{
    char destination[] = "hello ";
    char source[] = "world";
    printf("%s", ft_strcat(destination, source));
}

That's working but I got this encoding problem:

$ > ./a.out
hello wo"�o%
$ > ./a.out
hello wo"�Mj%
$ > ./a.out
hello wo"�Fn%

screnshot of the issue

2
  • 3
    1. Think about the following. What is the size of destination? What is the size of "hello world"? Can the latter fit in the first one? Commented Jul 16 at 23:57
  • 3
    2. Does the result "hello world" end with null-character? Commented Jul 17 at 0:02

2 Answers 2

5
  1. Your destination array is too small to accommodate both strings. It has only 7 elements. Declare it having enough (or more) elements and it will work:

    char destination[24] = "hello ";
    
  2. Your function does not null-terminate the string.

  3. You need to assign not to +=.

Example.

When you access an array outside its bounds you invoke undefined behaviour. When you use a non-null character terminated array as string you invoke another undefined behaviour.

Sign up to request clarification or add additional context in comments.

Comments

4

In addition to @0___________ good answer:

Advanced issues:

Huge strings

A string's length may be more than INT_MAX. Use size_t for array indexing and sizing rather than int.

dest and src overlap?

If there is buffer overlap, strange results may occur.

Either account for that or use restrict to indicate to the caller that the strings should not overlap. This also allows for select optimizations.

Common for the src string to be const

This allows for greater ft_strcat() application and helps some compilers optimize.


Altogether

// char *ft_strcat(char *dest, char *src);
char *ft_strcat(char * restrict dest, const char * restrict src);

Design issue: size

String functions deserve to have a size parameter to prevent buffer overflow. Perhaps as below. (I'd code it to have a well defined functionality on buffer overlap too.)

char *ft_strcat(size_t dest_size, dest[dest_size], const char *src);

To do: define what happens when the buffer size is insufficient.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.