I'm new to C programming and I'm currently trying to read a line from stdin using fgets(), but I'm having trouble with memory allocation since I'm using a char* to point to the string I want to read. When I execute the file it reports a segmentation fault.
This is the function I'm using:
char *read_line(char *line){ printf("%s",PROMPT); line = (char*)malloc(sizeof(char)*500); fgets(line,sizeof(line),stdin); printf("%s","pasa el fgets"); return line; } And my main:
void main(){ char line0; char *line=&line0; while(read_line(line)){ execute_line(line); } }
char line0; char *line=&line0;Nowlinepoints to acharbuffer of length 1. If your line is more than 1 byte in length, you'll overrun the buffer. Instead of just jamming code in until it compiles, try to actually understand what it is doing. I'd recommend a C tutorial, book, or course.sizeof(line)is the size of a pointer, not the size of the allocate memory.fgets(line,sizeof(line),stdin);-->fgets(line, 500, stdin);2)while(read_line(line)){-->while(line = read_line(line)){//need free(line); and break loop