runninoutofheap
runninoutofheap

Reputation: 23

Concatenating strings with special ending characters in C

I'm learning C and attempting to implement a function

char *es_cat(char *dst, char *src)

that adds the string src to the end of dst but with a little twist: The strings are considered to end with a '?' character instead of the usual '\0'. The string that's created has to end with a '?' but the first string's '?' is ignored. Here's my attempt:

/* A simple function to determine the length of a string according to the
 * previously stated '?' constraint.
 */
unsigned int es_length(const char *s)
{
    const char *c = s;
    int amount = 0;
    while (*c != '?')
    {
        amount++;
        c++;
    }
    return amount;
}

char *es_cat(char *dst, char *src)
{
    int total = es_length(dst) + es_length(src) + 1; // + 1 for the last '?'
    char buffer[total]; 
    char *b = buffer;

    /* Copy the dst string. */
    while (*dst != '?')
    {
        *b = *dst;
        dst++;
        b++;
    }

    /* Concatenate the src string to dst. */
    while (*(src-1) != '?')
    {
        *b = *src;
        src++;
        b++;
    }
    printf("\n%s", buffer);
    return buffer;
}

int main(void)
{
    char cat_dst[] = "Hello ?"; // length according to es_length = 6
    char cat_src[] = "there! - Well hel?"; // length according to es_length = 17
    es_cat(cat_dst, cat_src);
    return 0;
}

Now, when I run I'm expecting an output: Hello there! - Well hel?. The string is basically the same but is followed by 3 characters of trash (to be precise, the output is now Hello there! - Well hel?■@). When I add or remove 3 characters from the cat_src char array, the trash characters are gone. Am I initializing the buffer wrongly or am I messing something with the pointers?

On the other hand, would it be possible to concatenate the string dst directly i.e. not creating a buffer?

Thank you in advance!

Upvotes: 1

Views: 53

Answers (1)

user4207183
user4207183

Reputation:

Maybe your functions use a different string terminator, but you are using still standard C functions to print out the string, and they require a null terminator char, so that, at the end you have to write a null terminator into the string.

char *es_cat(char *dst, char *src)
{
    int total = es_length(dst) + es_length(src) + 2; // + 1 for the last '?' and +1 for the '\0'
    char *buffer = (char*)malloc(total);
    char *b = buffer;

    if (buffer == NULL)
        return NULL;

    /* Copy the dst string. */
    while (*dst != '?')
    {
        *b = *dst;
        dst++;
        b++;
    }

    /* Concatenate the src string to dst. */
    while (*src != '?')
    {
        *b = *src;
        src++;
        b++;
    }
    *b = '?';
    b++;
    *b = '\0';
    printf("\n%s", buffer);
    return buffer;
}

Upvotes: 1

Related Questions