I’m trying to write a simple program that takes in the users input, then prints it out. It’s to keep doing this until the user types "done".
When I run the code below, I input “01”, then get a Segmentation Fault ( core dumped ).
I think this has something to do with getline(), but I don’t know. I would appreciate it if someone could explain to me why it’s not working and how to fix it.
#include <stdio.h>
#include <stdlib.h>
int main(){
char* line;
size_t size ;
size = 100;
char* done;
done = "done";
printf("0");
while ( strcmp(line, "done") != 0 ) {
printf("1");
getline(&line, &size, stdin);
printf("2");
printf("%s\n", line);
}
return 0;
}
Here you just have a pointer that is pointing to nothing (actually garbage):
From the man page for getline():
So, note that you cannot use a stack-allocated buffer for getline.
The easier way to do this, is to initialize
lineto NULL and letgetlinehandle the allocation for you: