简体   繁体   中英

K&R exercise 1-18 gives segmentation fault when EOF is encountered

I've been stuck at this problem:

Write a Program to remove the trailing blanks and tabs from each input line and to delete entirely blank lines.

for the last couple of hours, it seems that I can not get it to work properly.

#include<stdio.h>
#define MAXLINE 1000

int mgetline(char line[],int lim);
int removetrail(char rline[]);

//==================================================================
int main(void)
{
    int len;
    char line[MAXLINE];

    while((len=mgetline(line,MAXLINE))>0)
        if(removetrail(line) > 0)
            printf("%s",line);

    return 0;
}
//==================================================================

int mgetline(char s[],int lim)
{
    int i,c;

    for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
        if( c == '\n')
        {
            s[i]=c;
            ++i;
        }
    s[i]='\0';

    return i;
}

/* To remove Trailing Blanks,tabs. Go to End and proceed backwards removing */

int removetrail(char s[])
{
    int i;

    for(i = 0; s[i] != '\n'; ++i)
        ;
      --i;  /* To consider raw line without \n */

    for(i > 0; ((s[i] == ' ') || (s[i] == '\t')); --i)   
        ; /* Removing the Trailing Blanks and Tab Spaces */

    if( i >= 0) /* Non Empty Line */
    {
        ++i;
        s[i] = '\n';
        ++i;
        s[i] = '\0';
    }
    return i;
}

I am using gedit text editor in debian.

Anyway when I type text into the terminal and hit enter it just copies the whole line down, and if I type text with blanks and tabs and I press EOF(ctrl+D) I get the segmentation fault.

I guess the program is running out of memory and/or using memory 'blocks' out of its array, I am still really new to all of this.

Any kind of help is appreciated, thanks in advance.

PS: I tried using both the code from the solutions book and code from random sites on internet but both of them give me the segmentation fault message when EOF is encountered.

It's easy:

The mgetline returns the buffer filled with data you enter in two cases:

  • when new line char is encountered
  • when EOF is encountered.

In first case it put the new line char into the buffer, in the latter - it does not.

Then you pass the buffer to removetrail function that first tries to find the newline char:

for(i=0; s[i]!='\n'; ++i)
    ;

But there is no new line char when you hit Ctrl-D ! Thus you get memory access exception as you pass over the mapped memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM