Search code examples
csegmentation-faultfgets

Segmentation fault randomly using fgets(), only happening on linux server not my own distro


Hey guys I am working on a program that is supposed to mimic some basic functions of tr. I have a bunch of tests that sometimes will pass and other times will segfault (Return 139). Ive been trying to figure this out for a while now and am honestly out of ideas.

char echo_array[256];
while ((fgets(echo_array, 255, stdin)) != NULL)
{
  for (int i = 0; echo_array[i] != EOF; i++)
  {
    for (int j = 0; j < strlen(argv[1]); j++){

      if (echo_array[i] == argv[1][j])
      {
        echo_array[i] = argv[2][j];
      }
    }
  }
  printf("%s", echo_array); 
}
return 0;

} }


Solution

  • The comparison echo_array[i] != EOF should be echo_array[i] != '\0'. Strings in C are terminated with a zero character, not with EOF.