Raj
Raj

Reputation: 1063

Output of printf() statement has not displayed properly when gets() function added

I have tried to use gets() library function in C and found that printf() statement output is delayed and got displayed after gets() receiving the input from stdin (i.e. from keyboard). Please check below C code and its output.

 #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
    int n, i, j;
    char ch, *str;

    printf("Enter size of input:\n");
    scanf("%d\n", &n);

    str = (char *) malloc(sizeof(char) * n);
    printf("Enter input string: \n");
    gets(str);

    printf("Given input string is : %s\n", str);
    return 0;
 }

Output:

Enter size of input: 9

R Raj Kumar <-- This name is given from input since program is waiting for input for gets() function even though printf("Enter input string\n") is present before gets() and printf() statement is not displayed on the console. It is getting printed after receiving gets() input from console.

Enter input string:

Given input string is : R Raj Kumar

Upvotes: 0

Views: 234

Answers (2)

Raj
Raj

Reputation: 1063

I have made changes in my program based on the comments/suggestions here. Below is the program that gives the right & desired output

Program:

#include<stdio.h>
 #include<stdlib.h>
 int main()
 {
    int n;
    char ch, *str;

    printf("Enter size of input:\n");
    scanf("%d", &n);

    while ((ch = getchar()) != EOF && ch != '\n');

    str = (char *) malloc(sizeof(char) * n);
    printf("Enter input string: ");
    fgets(str, n, stdin);

    printf("Given input string is : %s\n", str);
    return 0;
 }

Output:

Enter size of input: 9

Enter input string: R Raj Kumar

Given input string is: R Raj Ku

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70909

When you use gets(...) you need to have a buffer large enough to hold the input. Your input has 9 printed characters, but the actual input also has 2 spaces, and a terminating null character, so the size of your input is actually 12.

You have designed your program such that it is trivial to perform a buffer overflow. I suggest you read upon buffer overflows now, and learn to program defensively, avoiding buffer overflows.

Even if you are in a rush, reading up on how to avoid buffer overflows will save you time. The costs to fix a buffer overflow add up quickly, and far outweigh the time spent learning to avoid them.

Upvotes: 1

Related Questions