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!
int c;which is good — it allows you to test reliably for EOF). You may want to look at<ctype.h>andisspace()orisblank().