0

I am writing a function to read character input that has to consume leading white spaces before it begins to address the rest of the inputted line. I successfully read the leading whitespace characters of an input, if they exist. But for the life of me, I cannot figure out when I am getting seg faults when I try to read the rest of the line. I am using ansi C. Here is my code:

    void readCharLine(char **line_address) {
        int c;
        int index = 0;
        *line_address = malloc(35 * sizeof(char));
        c = getchar();

        /*Consume white spaces*/
        while ((c == ' ') && (index < 35)) {
            c = getchar();
            index++;
        }

        c = getchar();

        /*read rest of line*/
        while(c != '\n') {  
            *line_address[index] = c;
            c = getchar();
            index++;
        }
    }

I call readCharLine as follows:

    readCharLine(&node -> input);

where node is a struct declared as follows:

    /*Node declaration*/
    typedef struct {
        char *input;
        struct Node *next;
    } Node;

Thank you!

2
  • Note that you throw away the first (possibly only) non-blank character. You also need to test for EOF (you're using int c; which is good — it allows you to test reliably for EOF). You may want to look at <ctype.h> and isspace() or isblank(). Commented Feb 18, 2016 at 3:20
  • fix sample Commented Feb 18, 2016 at 3:21

1 Answer 1

1

Your are incrementing index even for the chars you discard, so chances are you are writing off the end of the array.

You probably also want while(c != '\n') { to be while(index < 35 && c != '\n') { - adjust as required depending on whether you need to 0 terminate the string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.