Remember To Malloc When Return A String

Consider the following function

char *my_strcat(char *s1, char *s2) {
  char newString[100];
  char *ptr = newString;

  while (*s1) {
    *ptr++ = *s1++;
  }

  while (*s2) {
    *ptr++ = *s2++;
  }

  *ptr = '\0';
  return newString;
}

This program simply will append s1 and s2 and produce a newString. However, this will not work because newString is created as a local variable and will be dispose after the function return.

Therefore after you return newString, the address points to nothing because the stack has already been disposed.

As a result, we need to use malloc instead so that it will reserves the memory and store in heap.

int my_strlen(const char *str) {
  int i = 0;

  while (*(str + i)) {
    i++;
  }

  return i;
}

char *my_strcat(char *s1, char *s2) {
  char *newString = (char *) malloc((sizeof(my_strlen(s1)) + sizeof(my_strlen(s2))) * sizeof(char));
  char *ptr = newString;

  while (*s1) {
    *ptr++ = *s1++;
  }

  while (*s2) {
    *ptr++ = *s2++;
  }

  *ptr = '\0';
  return newString;
}