0

I am attempting to reverse my lines within a text file using the recursion method. I am pretty stuck right now and my current output is a Segmentation Error- Can someone explain what the segmentation error is from and push me in the right direction?

void RecursionLine();
int main (int argc, char argv)
{
  RecursionLine();
  printf("\n");
}

void RecursionLine()
{
  int c;
if((c = getchar()) != EOF || (c != '\n'))
    {
      RecursionLine();
      printf("%c",c);
    }
 else if((c = getchar()) != EOF && (c == '\n')){
      printf("\n");
      RecursionLine();
}
}

Input: 
Dogs
Cats
Boys
Output
sgoD
staC
syoB
Barmar
  • 596,455
  • 48
  • 393
  • 495
Dnlfgby
  • 59
  • 8

1 Answers1

1

You are getting a Segmentation error because you have an || condition in your first if statement, where one of those conditions will always be true, causing your stack to overflow from infinite recursion! Change this to an && and it should be all fixed!

if((c = getchar()) != EOF && (c != '\n'))

EDIT: Additionally I believe you are going to run into some improper functionality due to the second getchar(). I would change your function to:

void RecursionLine()
{
  int c = getchar();
if(c != EOF || c != '\n')
    {
      RecursionLine();
      printf("%c",c);
    }
 else if(c != EOF && c == '\n'){
      printf("\n");
      RecursionLine();
}
}

Otherwise you are going to read in potentially 2 characters every iteration and that is going to cause one/both of them to be skipped!

Easton Bornemeier
  • 1,732
  • 5
  • 21
  • Thanks!! Dumb mistake, appreciate your help! – Dnlfgby Jun 22 '17 at 22:11
  • Note that declaring or defining a function with an empty parameter list is almost certainly not what you want. This is an obsolescent feature that means that the function, in this case `RecursionLine()`, takes an unspecified number of arguments. What you probably meant is: `void RecursionLine(void) {}`. The `void` is _necessary_ inside the parenthesis to signal that `RecursionLine()` takes no arguments. [See here](https://stackoverflow.com/questions/13950642/why-does-a-function-with-no-parameters-compared-to-the-actual-function-definiti)... – ad absurdum Jun 22 '17 at 23:28
  • [and here](https://stackoverflow.com/questions/18167390/what-does-an-empty-parameter-list-mean). Of course, it is correct to _call_ such a function with empty parenthesis: `RecursionLine();`. – ad absurdum Jun 22 '17 at 23:29