Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault upon input with getline()

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;
}
like image 969
Patrick Kennedy Avatar asked Nov 30 '25 05:11

Patrick Kennedy


2 Answers

Here you just have a pointer that is pointing to nothing (actually garbage):

char* line;

From the man page for getline():

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.

So, note that you cannot use a stack-allocated buffer for getline.

The easier way to do this, is to initialize line to NULL and let getline handle the allocation for you:

char* line = NULL;
int size = 0;
getline(&line, &size, stdin);   // line and size are updated with buffer addr and size.
//...
free(line);
like image 64
Jonathon Reinhart Avatar answered Dec 02 '25 22:12

Jonathon Reinhart


You are not allocating memory for:

char* line;

line is an invalid pointer before it points to a valid object. Use malloc to allocate memory, e.g., line = malloc(size);

like image 23
ouah Avatar answered Dec 02 '25 22:12

ouah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!