c - (linux)“分段错误(核心转储)”,同时将 char 指针传递给 c 中的函数
问题描述
每次尝试此功能时,我总是遇到错误“分段错误(核心转储)”:
int CheckFile(char * filename){
FILE * bd = fopen(filename, "r");
if(bd == NULL){
fclose(bd);
return -1;
}else{
fclose(bd);
return 0;
}
}
函数调用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_FILE_NAME "file.txt"
int CheckFile(char * filename);
int main(int argc, char ** argv[]){
char * name_of_file == NULL;
if(argc > 1){
printf("argc > 1\n");
for(i=0;argc>i;i++){
if(strcmp(argv[i],"-f")==0){
name_of_file = argv[i+1];
if(CheckFile(name_of_file) != 0)
printf("Can't find the file "%s".", name_of_file);
}
if(name_of_file == NULL){
if(CheckFile(DEFAULT_FILE_NAME) != 0);
printf("Can't find the default file \""DEFAULT_FILE_NAME"\".");
}
}
通过我的故障排除,我会说问题出在“char * filename”上,但找不到解决方法。有人可以帮帮我吗?我会很感激的。
解决方案
这具有未定义的行为,应该会崩溃或更糟:
if(bd == NULL){
fclose(bd);
空指针不是 的有效参数fclose
。只需删除对fclose
那里的调用。
推荐阅读
- ios - 如何在ios中创建没有tableview和collection view的行
- java - 如何将我的 java 程序复制到另一台计算机?
- function - 如何判断真/假然后返回一个函数
- asp.net - C# MVC 项目抛出 HTTP 错误 404.7 - Not Found 请求过滤模块配置为拒绝文件扩展名
- angularjs - 超过 50,000 条记录在 angularjs 的下拉列表中加载 ng-repeat
- windows - 天蓝色管道“命令行”代理作业是否从上一个作业继承工作目录?
- flutter - 有没有办法连接到安卓设备的激光扫描仪?
- python - Matplotlib ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
- python-3.x - Python '\r' 在同一行打印,但不会删除前面的文本
- google-chrome-extension - Chrome 扩展 newTab 和 amazon associates