Cesare
Cesare

Reputation: 9419

Why do strings get printed twice when using printf in C?

My program asks the user to provide a string, which will be copied into an array of characters. Then, with a for loop, the program simply copies the elements of the first array into the second array.

int main() {

    int i;
    char string1[4], string2[4];

    // Get the first string
    printf("Insert your string: ");
    scanf("%s", string1);

    // Copy the values into the second array
    for (i = 0; i < 4; i++) {
        string2[i] = string1[i];
    }

    // Print the second string
    printf("%s", string2);
    return 0;
}

However, when I print the string using the printf() function the string gets printed twice.

Let's say I input the word

bars

The output will be

barsbars

Why is this happening?

Upvotes: 5

Views: 3483

Answers (3)

Rounak
Rounak

Reputation: 611

char bString []= {'s','t','r','i','n','g'};               
printf("bString:%s\n", bString);

Output:

bString:stringstring

Solution: Always include the terminating character

char bString []= {'s','t','r','i','n','g','\0'};    

Or simply write:

char bString [] = "string";

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

Why?

TL;DR answer: undefined behaviour.

To explain, the problem here, with an input array defined like string1[4], (4 elements only), an input string like bars will be overruning the allocated memory region (in attempt to store the terminating \0), which in turn invokes undefined behaviour.

You should always take care of your input buffer length, like for an input array of string1[4], your scanf() should look like

scanf("%3s", string1);

Upvotes: 4

timrau
timrau

Reputation: 23058

char string1[4], string2[4];

4-element char array is not enough for 4-character strings. You need one more for the terminating '\0' character.

Upvotes: 6

Related Questions