Search code examples
cstringpointersmallocgarbage

Getting garbage inside my string


I'm writing a program which takes two strings and inputs one string into the other so that:

  • String 1: abc

  • String 2: 123

  • Output: a123b123c123

Now for some reason my output string gets garbage in the middle: a123=b123=c123. I have no idea why and would love some help!

Here's the code:

#define _CRT_SECURE_NO_WARNINGS
#define N 80
#define ONE 1
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

void InputStr(char str[]);
char* CreateString(char str1[], char str2[]);
int main()
{
    char strA[N], strB[N], *strF;

    InputStr(strA);
    InputStr(strB);
    strF = CreateString(strA, strB);
    puts(strF);

}

void InputStr(char str[])
{

    printf("Please enter the string\n");
    scanf("%s", str);


}
char* CreateString(char str1[], char str2[])
{

    char* newstr;
    int len1, len2, size, i, j, b;
    len1 = strlen(str1);
    len2 = strlen(str2);
    size = len1*len2;
    newstr = (char*)malloc(size*sizeof(char) + 1);
    for (i = 0, b = 0; i<len1; i++, b++)
    {
        newstr[b] = str1[i];
        b++;
        for (j = 0; j<len2; j++, b++)
            newstr[b] = str2[j];


    }
    newstr[b + ONE] = 0;
    printf("test\n");
    return newstr;


}

Solution

  • Your problem

    You are incrementing your b variable 2 times:

    for (i = 0, b = 0; i < len1; i++, b++) // First increment
    {
        newstr[b] = str1[i];
        b++; // Second increment
        for (j = 0; j < len2; j++, b++)
            newstr[b] = str2[j];
    }
    

    Solution

    Just remove the first b increment and you code will work:

    for (i = 0, b = 0; i < len1; i++) // No more b increment
    {
        newstr[b] = str1[i];
        ++b; // You only need this increment
        for (j = 0; j < len2; j++, b++)
            newstr[b] = str2[j];
    }