首页 > 解决方案 > (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”上,但找不到解决方法。有人可以帮帮我吗?我会很感激的。

标签: clinuxpointerschararguments

解决方案


这具有未定义的行为,应该会崩溃或更糟:

if(bd == NULL){
    fclose(bd);

空指针不是 的有效参数fclose。只需删除对fclose那里的调用。


推荐阅读