0

I want to get rid of buffer overflow and I am using fgets instead of scanf to limit the characters. But whenever I enter something with scanf before fgets, it doesn't work correctly anymore.

This code works correctly

#include <stdio.h>
int main()
{
 char name[10];
 printf("Who are you? \n");

 fgets(name,10,stdin);                   

 printf("Good to meet you, %s.\n",name);
 return(0);
}

This code does not read name correctly

#include <stdio.h>
#include <stdlib.h>
#define MAX 15

int new_acc();
int view_list();
int main(){    
    int one=1, two=2, three=3, four=4, five=5, six=6, seven=7, choice;
    int new_account, list;

    printf("%d. Create new account\n",one);

    printf("Enter you choice: ");
    scanf("%d",&choice);

    if (choice==one){new_account = new_acc();}
    return 0;
}

int new_acc(){
    char name[MAX], address, account;

    printf("Enter your name: ");
    fgets(name, MAX, stdin);          /* it is the code */
}

Why is it happening and how do I fix it?

miloserdow
  • 1,051
  • 1
  • 7
  • 27
  • 1
    Consume `\n` before calling `fgets()` – Arkadiusz Drabczyk May 06 '20 at 18:31
  • Does this answer your question: [scanf leaves new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer/5240807?r=SearchResults#5240807) – Isaiah May 06 '20 at 18:34

1 Answers1

1

Don't mix scanf() with fgets() in the same code.

scanf("%d",&choice); does not consume all the line - it leaves the trailing '\n' for the later fgets() to consume as an empty line.

scanf() is difficult to use in a secure fashion.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256