简体   繁体   中英

I'm getting Segmentation fault (core dumped) while using getline

Here's my code:

char* ReadOneLine(char *FileName)
{
  FILE *FilePointer = fopen(FileName, "r");
  assert(FilePointer != NULL);
  char* new_line = NULL;
  size_t *line_lenght = 0;
  //ssize_t line_size;
  getline(&new_line, line_lenght, FilePointer);
  assert(new_line == NULL);
  return(new_line);
}


int main()
{
  char* buffer = ReadOneLine("example"); //Buffer will do somthing later...
  return (0);
}

I keep getting this error while trying to run the program and I can't understand why. Plus I know I'm supposed to free new_line after using it but I'm not sure where because I'm sending new_line to other functions as well.

The pointer line_lenght doesn't point anywhere. It contains a NULL pointer. So when getline tried to dereference this null pointer you invoke undefined behavior which in this case results in a crash.

Instead of defining line_lenght as a size_t * , define it as size_t and pass its address.

size_t line_length = 0;
getline(&new_line, &line_length, FilePointer);

As for where to call free , since ReadOneLine returned the malloced buffer then the function that called ReadOneLine needs to call free . In this case, than means you need to call free(buffer) in the main function when you're done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM