vendredi 1 juillet 2016

Segmentation fault - suspected die on fflush(STDOUT)

I am working on a unit test which will use FILE* stream to mimic STDIN. The function will get called everytime there's a need to input the value(In this case function get called for 3 times). The code works fine until 3rd call,where i got an error:

Received signal 11 (Segmentation fault)

Is anyone know why segmentation fault happened?

I tried to printf line by line & it seems like the code dead at fflush(stdout). Is anyone know what happened?

int readInput(char *prmt,char *defaultValue,char *input)
{
  char ch, inValue[200], tmpString[200];
  int  count;

  if (strcmp(defaultValue,"")){
    sprintf(tmpString,"%s (%s) ",prmt,defaultValue);
  }

  fprintf(stdout,"%s ",tmpString);
  ch=' ';
  count=0;
  while (ch!='\n') {
    ch = getc(stdin);
    if (feof(stdin) || ferror(stdin)) {
      inValue[0]='\0';
      exit(0);
    }
    inValue[count]=ch;
    count++;
  }

  fflush(stdout);

  inValue[count-1]='\0';
  if (strcmp(inValue,"") && (inValue[0]!=';')) {
    strcpy(input,inValue);
  } else {
    strcpy(input,defaultValue);
    if (inValue[0]==';')
      return(FALSE);
  }

  return(TRUE);
} 

The file that used to mimic for series of STDIN as below($ means endline)

john$
16$
student$

Aucun commentaire:

Enregistrer un commentaire