Search code examples
cstringstrlen

Garbage values; strange string strlen value


I am trying to write a function that inserts one string into another string at a specified value. It is returning a few garbage values toward the end of the new string, presumably because, for some reason, the strlen of the new string is greater than what it should be; strlen(combo) should equal s1 + s2 but it does not. I am not sure why it is returning 13 instead of 9 as the length. Here's my code:

#include <stdio.h>
#include <string.h>

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i < s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

EDIT: Added the null character. Still returning a single garbage value several spaces to the right of the new string, and still not returning 9 as the proper string length.

#include <stdio.h>
#include <string.h>

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i <= s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i == s1 + s2) {
            combo[i] = '\0';
        }
        else if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

Solution

  • You are lacking a terminating \0 in your combo string. strlen() returns the length excluding the terminating null-byte.