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);
}
}
The main mistake is to pass the pointer
line
to the functionread_line
(by value) and try to modify it in that function.read_line
allocates the memory and actually creates the pointer value. So it should be able to change the value ofline
inmain
:Or, you use the return value of
read_line
in order to modifymain
'sline
. In that case you don't need the parameter at all:Additional errors (pointed out by Jonathon Reinhart) and remarks:
sizeof
does not "work" for pointers (array decayed to pointers).malloc
many stringsline
but you do notfree
them.sizeof(char)
is always 1.malloc
should be avoided.