Beryllium Nitrate
Beryllium Nitrate

Reputation: 11

How to fix segmentation fault: 11 compiler error

I have been learning from the C Programming Language book (K&R) and was writing one of the exercises that removes trailing blanks from an input. I understand that a segmentation fault is at some level a problem having to do with accessing memory that is not accessible, but I have read through this code several times and can't find the error. I would like it very much if someone could help find this error and tell me how to discover errors like this in the future.

#include <stdio.h>

#define MAXLINE 1000
#define CHAR 0 /*character definition*/
#define TRAIL 1 /*determines whether program is in a trailing blank*/

int getinput(char input[], int max);
int trailrem(char input[], char copyto[]);
int len;

int main() {
    char line[MAXLINE]; /*current line*/
    char newline[MAXLINE];
    int i, c, newreturn; /*integer counter, character holder, current line       length, and trailrem return value*/
    int len;

    while((len = getinput(line, MAXLINE)) > 0) {
        newreturn = trailrem(line, newline);

        for(i = 0; i <= newreturn; ++i)
            printf("\n%c\n", newline[i]);
    }

 }

int getinput(char input[],int max) {
    int i, c, line;
    for(i = 0; (c = getchar()) != EOF && c != '\n' && c < (max-1); ++i)
        input[i] = c;

    if(c == '\n') {
        input[i] = c;
        ++i;
   }

    input[i] = '\0';
    return i;
}

int trailrem(char input[], char copy[]) {
    int i, j, minusin, state, r;

    for(i = len; input[i] != EOF && i >= 0; --i) {
        if(input[i] =='\n')
            state = TRAIL;

        else if((input[i] == ' ' && state == TRAIL) ||( input[i] == '\t' && state == TRAIL))
            ++minusin;

        else if(state == TRAIL && (input[i] != ' ' || input[i] != '\t'))
            state = CHAR;

        for(j = (r = len-minusin); state == CHAR; --j){
                copy[j-2] = input[i];
        }
    }


    copy[r] = '\0';
    copy[r-1] = '\n';
    return r;

}

Upvotes: 0

Views: 679

Answers (1)

mazhar islam
mazhar islam

Reputation: 5629

So many problems in your code. But the main problem is, you have a global len

int len; 

And a local len in the main function.

You are initializing len in main function like this:

while((len = getinput(line, MAXLINE)) > 0)

So the local len is updated. But the global len is still 0.

You are expecting that, you will get the updated value of len in trailrem method but you don't. In trailrem() you will get len equal to 0!

for(i = len; input[i] != EOF && i >= 0; --i)

So i is 0 too. And hence, copy[r-1] = '\n'; will crash, because r-1 can be negative.

Other problems: (BLUEPIXY and WhozCraig mentioned in the comment).

for(i = 0; (c = getchar()) != EOF && c != '\n' && c < (max-1); ++i)

here, c < (max-1) should be i < (max-1).

++minusin; in trailrem function where minusin is uninitialized.

Upvotes: 4

Related Questions