I am making a program that has the user enter in a line of text, and the program then prints it back to them. They way I have done it - more specifically with the char *read_line()
method - is in a way I have to for my homework.
When the user enters in something (such as their name) and presses enter, it just says, 'Segmentation fault (core dumped)' and I don't know why.
#include <stdio.h>
char *read_line(char *buf, size_t sz) {
if (fgets(buf, sz, stdin) && buf[0] != '\n' )
{
return buf;
}
else
{
return NULL;
}
}
int main(int argc, char** argv) {
char *buf;
char *p;
p = read_line(buf, 1024);
if (p != NULL) {
fputs(p, stdout);
}
return 0;
}
char *buf;
You've declared a pointer to a char
here, but have not initialized it. Therefore, it's value is whatever was on the stack when your function is called.
When you attempt to access the memory it points to, which is some random memory address, that's almost certainly going to be an illegal memory access.
Either use malloc()
to allocate some memory to point to (don't forget free()
), or set the variable to the address of another variable.