【问题标题】:Segmentation fault reading random lines of text?读取随机文本行的分段错误?
【发布时间】:2020-07-26 12:17:09
【问题描述】:

我已经阅读了很多关于这个主题的文档,但我仍然有一些问题,我知道指针是什么,但是当我尝试使用时我遇到了一些问题,在下面的代码中,txt 文件每个只包含一个单词行。我尝试从文本中读取随机行并返回到主函数,因为我需要这个)。我在主函数中打印它,请你帮我在这段代码中更改哪个部分?(当我尝试运行此错误消息是分段错误(核心转储))

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

char word(char *file, char str[], int i);

int main() {
  char buf[512];

  char j = word("words.txt", buf, 512);
  puts(j); // print random num
}

char word(char *file, char str[], int i) {
  int end, loop, line;

  FILE *fd = fopen(file, "r");
  if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  srand(time(NULL));
  line = rand() % 100 + 1; // take random num

  for (end = loop = 0; loop < line; ++loop) {
    if (0 == fgets(str, sizeof(str), fd)) { // assign text within a random line to STR
      end = 1;
      break;
    }
  }
  if (!end)
    return (char*)str; // return the str pointer
  fclose(fd);
}

【问题讨论】:

  • char str 作为函数参数是可疑的,sizeof(str)
  • 另外你为什么要打开文件两次?
  • 你说得对,我没有必要编辑,但我仍然不明白这段代码有什么问题,我不明白为什么 char str 作为参数是可疑的?
  • 因为它不包含字符串(一个单词),而只包含一个字符,例如 `a' 或 '\n'。
  • fgets 需要一个字符 *,所以是一个地址。相反,您传递的是一个字符。尝试写入不是真实地址 = 段错误的地址。

标签: c arrays pointers random return-type


【解决方案1】:

您重新打开了文件,可能是这种情况。如果文件在 if(!end) 部分返回 fd 未关闭,则您不会关闭该文件。 该函数需要 char 但实际上需要 char *

char word(char *file, char str, int i);

int main() {
  char * buf = malloc(sizeof(char)*512);
  char *words = "words.txt";
  char* j = word(words, buf, 512);
  puts(j); // print random num
}

char word(char *file, char str[], int i) { // FIX HERE
  int end, loop, line;

  FILE *fd = fopen(file, "r"); // 
  if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  srand(time(NULL));
  line = rand() % 100 + 1; // take random num

  for (end = loop = 0; loop < line; ++loop) {
    if (0 == fgets(str, sizeof(str), fd)) { // MAIN PROBLEM, PUT A CHAR* TO STR. 
      end = 1;
      break;
    }
  }
fclose(fd); // YOU DIDN'T CLOSE IF IT RETURNED BEFORE
  if (!end)
    return str; // return the str pointer

//NOTHING IS RETURNED HERE
return str;
// I guess the problem is here, you return nothing and the function finishes, and you try to write that nothing with puts function which may cause a seg fault.
}```

【讨论】:

  • 我编辑了 char word(char* file,char* str); 并返回 (char*)str 但仍然有错误,我添加了 else printf("hi");在关闭 fd 之前仍然存在段错误。
  • 我试了代码,发现错误!你在 puts 函数中给出了一个字符。我编辑了代码,现在试试,请接受我的答案作为问题的答案,我需要声誉。
  • 感谢您的回答我编译它但仍然存在分段错误和一些警告,它们是:从 'char' 初始化 'char *' 使指针从整数而不进行强制转换(14.13),数组函数参数 'str' 上的 sizeof' 将返回 'char *' 的大小,从返回类型为 'char' 的函数返回 'char *' 从没有强制转换的指针生成整数(38.12),从 a 返回 'char *'返回类型为“char”的函数从没有强制转换的指针生成整数(41.8)
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多