分段错误(核心转储) [英] Segmentation Fault(core dumped)

查看:182
本文介绍了分段错误(核心转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿家伙我有这个code:(IM试图读取一个字符串,并把它放在输出文件中)

hey guys i have got this code: (im trying to read a string and put it inside the output file)

#include "structs.h"
#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE* input = fopen("journal.txt", "r");
  FILE* output = fopen("output.txt", "w");
  char date[9];

  if( ferror(input) || ferror(output) ) {
    perror("Error opening input/output file\n");
  }

  fscanf(input, "%s", date);
  fgets(date, 9, input);
  fputs(date, output);
  fclose(input);
  fclose(output);
  return 0;
}

它正确编译但在运行时它显示错误

it compiles properly but at runtime it shows the error

 Segmentation fault (core dumped)

我不知道为什么:(请帮助

i have no idea why :( please help

推荐答案

您需要检查是否的fopen 收益 NULL

#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE * input;
  FILE * output;
  char date[9];

  input = fopen("journal.txt", "r");
  if(input == NULL){
    perror("Could not open input file");
    return -1;
  }

  output = fopen("output.txt", "w");
  if(output == NULL){
    perror("Could not open output file");
    fclose(input);
    return -1;
  }
/* ... snip ... */

您输入文件可能不存在。在调用分割故障 FERROR NULL 的结果。

Your input file probably doesn't exist. Calling ferror on NULL results in a segmentation fault.

这篇关于分段错误(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆