1

I am trying to write a program that removes trailing spaces/tabs from input lines (Exercise 1-18 from K&R).

/* Write a program to remove trailing blanks and tabs from each
line of input, and to delete entirely blank lines. */

#include <stdio.h>
#define MAXLINE 1000

int gettline(char s[], int lim);

main()
{
    int len, i;
    char line[MAXLINE];
    while ((len = gettline(line, MAXLINE)) > 0)
        for(i=0; i<len-1; ++i){
            if (line[i]!= ' ' && line[i]!='\t')
                printf("%s", line[i]);
        }
    printf("\n");   
    return 0;
}

/* gettline: read a line into s, return length */
int gettline(char s[], int lim)
{
    int c, i;
    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;
}

When I run it I get the error Segmentation fault (core dumped). I viewed some other SO questions with the same theme (1, 2, 3, 4,..) but they were too complex for my level. I only know that the error means I tried to access part of the memory I wasn't allowed to. I am not sure where exactly this happened in my case

Community
  • 1
  • 1
Omid
  • 2,617
  • 4
  • 28
  • 43
  • Is there a reason you are not using `fgets` to read your file line by line? – Sergey L. Sep 09 '14 at 13:31
  • I am sorry, but I am a total beginner in C and I am reading K&R from the beginning. I am supposed to solve the problem with no use of libraries. @Vladp Hm, no. I only ran it through valgrind and it gave no errors. – Omid Sep 09 '14 at 13:35

1 Answers1

3

The reason for the seg fault should be this:

    for(i=0; i<len-1; ++i){
        if (line[i]!= ' ' && line[i]!='\t')
            printf("%s", line[i]); 
    }

Because of %s, printf() expects a char * argument but you pass a single character. Change it to printf( "%c", line[i] ); and it should run.

But it still wouldn't do what you say you want to achieve ("remove trailing spaces/tabs") because you wouldn't print any spaces or tabs, " Hello World " would become "HelloWorld"

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33