【问题标题】:Seg fault before main even runs?主要事件运行之前的段错误?
【发布时间】:2016-01-27 17:01:22
【问题描述】:

在我的主程序运行任何能够导致段错误的重要代码之前,我就收到了段错误。也就是说,printf("before main functionality starts\n"); 没有运行。

什么可能导致这个问题?

 int main() {
  printf("before main functionality starts\n"); 
  person* people = create();
  
  //Make new file and write into it
  printf("\nWriting into file\n");
  char file_name[] = "people_list";
  int file_number = open(file_name, O_CREAT|O_WRONLY, 0644); //only owner can read/write, rest can only read

  int error_check;
  error_check = write(file_number, people, sizeof(&people) ); //reads array into file
 
  if(error_check < 0) {
    printf("ERROR: %s\n", strerror(errno));
    return -1;
  }
  close(file_number);

  //Read from new file
  printf("\nReading from file...\n");
  person* new_people[10];
  file_number = open(file_name, O_RDONLY); //reopens file, now with data
  error_check = read(file_number, new_people, sizeof(people));
  if(error_check < 0) {
    printf("ERROR: %s\n", strerror(errno));
    return -1;
  }
  close(file_number);

【问题讨论】:

  • 将代码放在问题中而不是屏幕截图是首选
  • 我很抱歉。发展偏头痛,我的终端拒绝与我的复制粘贴企业合作。
  • 您出现了段错误,因为您正在取消引用未初始化的指针 (first)。您没有看到“woops”是因为您没有刷新输出流,而不是因为没有调用 printf
  • 你能解释一下刷新输出流是什么意思吗?我对 C 语言还是比较陌生。
  • @CodeSammich 如果 C 运行时在每次写入标准输出流时都会自动刷新它,那么对于printf 来说这将是一件极其昂贵的事情。相反,每次遇到换行符时它都会刷新流缓冲区。您可以通过在字符串 "woops\n" 的末尾打印一个换行符来导致刷新,在下一个换行符 fflush(stdout) 之前显式刷新它或使用无缓冲输出 fprintf(stderr, "woops")

标签: c segmentation-fault main


【解决方案1】:

如果您想立即查看输出,则需要刷新句柄(使用fflush(stdio))。您的程序很可能在立即发出 printf 调用后崩溃。

IO 也会在行尾刷新,因此如果您的调试语句以 '\n' 结尾,那么它将显示出来,您会发现发生分段错误的位置。

【讨论】:

  • 用 fflush(stdio) 刷新;
  • 选择这个作为答案:与标题中的问题更相关。
  • fflush(stdio);之前使用FILE* stdio = stdout;FILE* stdio = stderr;
【解决方案2】:

在图像中可以看到您有未分配内存来构造。

分配内存给结构指针firstnew,然后用它们来访问结构成员。

person *first=malloc(sizeof *first);             //remember to free allocated memory

【讨论】:

  • 如果指针驻留在同一个方法(main)中,我们不需要分配内存吗?编辑:它有效,但我仍然不清楚 malloc 的原因
  • @CodeSammich 指针不需要分配。但它需要指向某些东西,而这通常是一个动态分配的对象。如果您不想使用动态分配,您只需编写 person first; 而不使用指向树根节点的指针。
  • @CodeSammich 您需要初始化指针,而且 C 没有方法 :-)
  • @ameyCU 哎呀,我的意思是函数*我明白了。谢谢! (我真的需要睡觉......)
  • @CodeSammich 不要无缘无故过度使用malloc。如果你的struct persons 实现总是可见的,那么更喜欢自动持续时间(普通变量而不是malloced 变量)。
猜你喜欢
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 2013-11-13
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多