This is a C program that should accept the terminal's input and return the longest line of the input alongside the length of that line. I know it's not as efficient as it could be made, but I'm trying to write with the few functions I know right now. In running it, it returns a segmentation error. An online debugger points out line 30 (which is flagged in the code below) but doesn't specify the problem. I'm not sure of it either, and I've been looking. What is the source of this error?
By the way, I know that there might be other errors. I want to find those myself. I only need help with that segmentation error.
#include <stdio.h>
#define MAX 200
int start = 0;
int i, j, k, x, finish;
int longlength;
char text[MAX];
char longest[MAX];
int main()
{
fgets (text, MAX, stdin);
for (i = start; text[i] != EOF; i++)
{
if (text[i] == '\n')
{
finish = i - 1;
break;
}
}
for (j = start; j <= finish; j++)
{
longest[j - start] = text[j];
}
longlength = finish - start;
for (k = finish + 1; (text[k] = '\n') && (text[k] != EOF); k++)
{
start = k; //*****This is line 30*****
for (i = start; (text[(i + 1)] != '\n') && (text[(i + 1)] != EOF); i++)
{
}
finish = i;
if ((finish - start) > longlength)
{
longlength = (finish - start);
for (x = start; x <= finish; x++)
{
longest[(x - start)] = text[x];
}
}
}
printf ("This is the longest line : %s.\n Its length is %d.", longest, longlength);
return 0;
}
EOF(end of file) and not for\0?fgetsfunction writes a null-terminated byte string to the destination array. Also note that there are cases wherefgetswill not write the newline to the destination array, which means you could continue the program withfinishequal to zero. You should also make sure thefgetscall doesn't fail, which it indicates by returning aNULLpointer.strcmpandstrcpy.\nand checked against EOF. So the loop should run forever.