C get 行中的分段错误

Segmentation fault in C get line

我需要读取一个文件,为此我正在使用函数 getline。以下是该网站的示例:http://crasseux.com/books/ctutorial/getline.html 我为了能够打开文件而进行了调整。

#include <stdio.h>
#include <stdlib.h>


int main()
  {
  int bytes_read;
  unsigned long nbytes = 100;
  char *my_string;
  char *filename;
  char *line;
  FILE *fd = NULL;


  puts ("enter filename");

  filename = (char *) malloc (nbytes + 1);

  bytes_read = getline (&filename, &nbytes, stdin);

  fd = fopen(filename, "r");

  bytes_read = getline (&line, &nbytes, fd);

  puts (line);

  puts ("Please enter a line of text.");

  /* These 2 lines are the heart of the program. */
  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, stdin);

  if (bytes_read == -1)
    {
      puts ("ERROR!");
    }
  else
    {
      puts ("You typed:");
      puts (my_string);
    }

  return 0;
}

当我 运行 程序出现分段错误 11 时,我不知道自己做错了什么。提前谢谢你。

或者

  • 使 line 指向一些有效的内存并 nbytes 指向内存的大小

  • 或将 line 设置为 NULL,将 nbytes 设置为 0

来自 man getline:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line.

另外 getline() 期望 size_t 作为第二个参数而不是 unsigned long

另外 ^2 不需要多分配 1 个字节然后传递给 getline。分配n字节并传递n,无需传递n - 1


并且总是在相关系统调用中添加错误检查,例如 malloc()fopen() 在使用它们 return.

的结果之前

您从标准输入读取的 filename 文件文件参数是错误的。例如,当输入 a.txt 时,filename 从 stdin 获取的 str 值是 'a.txt\n'。

所以,添加一条将'\n'修改为'\0'的语句将解决问题。即在 bytes_read = getline (&filename, &nbytes, stdin); 语句正下方添加 filename[bytes_read - 1] = '[=14=]'; 语句。

#include <stdio.h>
#include <stdlib.h>


int main()
  {
  int bytes_read;
  unsigned long nbytes = 100;
  char *my_string;
  char *filename;
  char *line;
  FILE *fd = NULL;


  puts ("enter filename");

  filename = (char *) malloc (nbytes + 1);

  bytes_read = getline (&filename, &nbytes, stdin);

  filename[bytes_read - 1] = '[=10=]';

  fd = fopen(filename, "r");

  bytes_read = getline (&line, &nbytes, fd);

  puts (line);

  puts ("Please enter a line of text.");

  /* These 2 lines are the heart of the program. */
  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, stdin);

  if (bytes_read == -1)
    {
      puts ("ERROR!");
    }
  else
    {
      puts ("You typed:");
      puts (my_string);
    }

  return 0;
}