Question

This piece of code should concat 2 strings, but I'm getting Bus error: 10. I've researched about it, so I gave t1 more space, but I'm still getting that error. Can you help me out? Thanks in advance!

char *strCat (char s1[], char s2[])
{
    int i=0,j=0;

    while (s1[i++]);

    while (s2[j])
    {
        s1[j++] = s2[j++];
    }

    s1[j] = '\0';

    return s1;
}

int main()
{
    char t1[10] = "asd";
    char t2[] = "fgh";
    printf("%s", strCat(t1,t2));
}
Was it helpful?

Solution

There are a few things wrong with this segment of code.

while (s2[j])
{
    s1[j++] = s2[j++];
}

Because j++ is being executed twice in the same line, you're invoking undefined behavior. This will go away if we move the j++ to its own line:

while (s2[j])
  {
    s1[j] = s2[j];
    j++;
  }

There are two more issues with your code. First, you use one counter (i) to get to the end of s1, but don't use it when appending s2 to s1. Let's fix that:

while (s2[j])
  {
    s1[i] = s2[j];
    i++;
    j++;
  }

We'll need to do the same thing when appending the trailing \0 to s1:

s1[j] = '\0';

becomes

s1[i] = '\0';

Second is a minor off-by-one bug with i.

while (s1[i++]);

If you mentally trace through this, i++ will evaluate once more than you want, putting i at 4 when the loop ends. However, at this point, there are only three characters in s1: asd. a = character 0, s = character 1, d = character 2. We want to start writing s2 one character past this, so we want to start writing from character 3. Adjusting your loop to match,

while (s1[i++]);
i--;

You could also do this for clarity's sake:

while (s1[i])
{
  i++;
}

Now, putting it all together:

#include <iostream>

char *strCat(char s1[], char s2[])
{
  int i = 0, j = 0;

  while (s1[i])
  {
    i++;
  }

  while (s2[j])
  {
    s1[i] = s2[j];
    i++;
    j++;
  }

  s1[i] = '\0';

  return s1;
}

int main()
{
  char t1[10] = "asd";
  char t2[] = "fgh";
  printf("%s", strCat(t1, t2));
}

And this works as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top