【问题标题】:I'm getting Segmentation fault (core dumped) while using getline使用 getline 时出现分段错误(核心转储)
【发布时间】:2019-04-01 16:46:13
【问题描述】:

这是我的代码:

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);
}

我在尝试运行程序时不断收到此错误,我不明白为什么。 另外,我知道我应该在使用 new_line 后释放它,但我不确定在哪里,因为我也在将 new_line 发送到其他函数。

【问题讨论】:

  • 程序使用完毕后将代码添加到free这一行。

标签: c segmentation-fault


【解决方案1】:

指针line_lenght 没有指向任何地方。它包含一个 NULL 指针。因此,当getline 尝试取消引用此空指针时,您会调用undefined behavior,在这种情况下会导致崩溃。

不要将line_lenght 定义为size_t *,而是将其定义为size_t 并传递其地址。

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

至于在哪里调用free,由于ReadOneLine返回了分配的缓冲区,那么调用ReadOneLine的函数需要调用free。在这种情况下,这意味着您完成后需要在 main 函数中调用 free(buffer)

【讨论】:

  • 也许也可以修正拼写:-)
猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
相关资源
最近更新 更多