1

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); } } 
5
  • char line0; char *line=&line0; Now line points to a char buffer 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. Commented Nov 3, 2016 at 22:05
  • 1
    So many errors in so few lines of code ;-) Commented Nov 3, 2016 at 22:05
  • 2
    sizeof(line) is the size of a pointer, not the size of the allocate memory. Commented Nov 3, 2016 at 22:06
  • 1) 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 Commented Nov 3, 2016 at 22:07
  • @JonathonReinhart so you suggest a malloc there? Commented Nov 3, 2016 at 22:10

1 Answer 1

2

The main mistake is to pass the pointer line to the function read_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 of line in main:

char *read_line(char **line){ ... *line = malloc(500); fgets(*line, 500, stdin); ... return *line; } int main(void) { char *line; while(read_line(&line)){ ... } } 

Or, you use the return value of read_line in order to modify main's line. In that case you don't need the parameter at all:

char *read_line(void) { char *line; ... line = malloc(500); fgets(line, 500, stdin); ... return line; } int main(void) { char *line; while(line = read_line()){ ... } } 

Additional errors (pointed out by Jonathon Reinhart) and remarks:

  1. sizeof does not "work" for pointers (array decayed to pointers).
  2. You malloc many strings line but you do not free them.
  3. sizeof(char) is always 1.
  4. Some people (me too) think that casting the result of malloc should be avoided.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.