LP Jeev
LP Jeev

Reputation: 15

Concatenate two strings without using strcat

I wrote a function to concatenate two strings (s = "computer"; t = "keyboard"), but my code only returns "keyboard". Please point out the mistakes.

char *concat(char *s, char *t) {
    s = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
    char *p = s;
    while (*p != '\0') {
        ++p;
    }
    while (*t != '\0') {
        *p++ = *t++;
    }
    *p = '\0';
    return s;
}

I do not want to use strcat(). This is a test program from Stepik, so I cannot change anything in the main function. Here is the question: Write a function which receives two character pointers and returns a new character pointer representing their concatenation.

Upvotes: 1

Views: 2195

Answers (3)

chqrlie
chqrlie

Reputation: 144770

You are on the right track:

  • you allocate the correct amount of memory,
  • you copy the second string correctly,
  • you set the null terminator correctly,
  • you return the pointer to the allocated block.

Yet there are some issues:

  • you overwrite the pointer to the first string with that returned by malloc(),
  • you read from the allocated memory block instead of copying the first string: this has undefined behavior,
  • (minor) the argument strings should be declared as const char * as you do not modify these strings.

Here is a corrected version:

#include <stdlib.h>
#include <string.h>

char *concat(const char *s, const char *t) {
    char *ret = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
    char *p = ret;
    while (*s != '\0') {
        *p++ = *s++;
    }
    while (*t != '\0') {
        *p++ = *t++;
    }
    *p = '\0';
    return ret;
}

Upvotes: 0

0___________
0___________

Reputation: 67546

char *myconcat(const char *s1, const char *s2)
{
    size_t len1,len2;
    char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);

    if(result)
    {
        memcpy(result, s1, len1);
        memcpy(result + len1, s2, len2 + 1);
    }
    return result;
}

Upvotes: 2

Roman2452809
Roman2452809

Reputation: 448

You have s="computer" when passed into a function, and then on the very first line you reassign it with malloc, so "computer" is gone. You can debug your program step by step, or just print the values to the console. This will help you to find the error.

Upvotes: 0

Related Questions