Home > Enterprise >  C input methods from security and bug free point of view?
C input methods from security and bug free point of view?

Time:01-23

I made the following code and i want to know if this is the best method of string input in C from security and bug free point of view.

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

#define MSG_LEN 25

int main(){

  char msg[MSG_LEN];
  int i;
  
  while(1) {
    putchar(':');
    fgets(msg, MSG_LEN, stdin);
    for(i = 0; i < strlen(msg); i  ){
    putchar(msg[i]);}
    if (strlen(msg) == MSG_LEN - 1) putchar('\n');
    while (strlen(msg) == MSG_LEN - 1) fgets(msg, MSG_LEN, stdin);
  }
  return 0;
}

Finally i found the solution for my question after bumping my head against the wall for some time. Anyone got any improvement for this code? I give most of credit to Simon Goater.

CodePudding user response:

The main issues with user input in c are avoiding buffer overflows, which your code does, and draining/truncating the input that is longer than the given buffer allows. If you don't drain the remaining data, it can be read in again without blocking on the next fgets and give undesirable results. I've modified your code to loop so that the draining feature can be shown.

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

#define MSG_LEN 25

int main(){

  char msg[MSG_LEN];
  while(1) {
    puts(":");
    fgets(msg, MSG_LEN, stdin);
    printf("%s", msg);
    if (strlen(msg) == MSG_LEN - 1) printf("\n");
    while (strlen(msg) == MSG_LEN - 1) fgets(msg, MSG_LEN, stdin);
  }
  return 0;
}
  • Related