注册 登录
编程论坛 C语言论坛

fclose()关闭文件崩溃问题

lvhui123456 发布于 2021-01-27 16:02, 2142 次点击
本地随便创造四个文件,我的环境是有single_node_boolean.sql; single_node_char.sql; single_node_name.sql; single_node_varchar.sql;四个文件做测试。
在字符串切割后的文件名去读取和关闭文件时,崩溃掉。
请求哪位大神能帮忙分析下原因?非常感激!!

程序代码:
#include <stdio.h>
#include <malloc.h>
#include <ctype.h>
#include <string.h>

bool file_exists(const char* file)
{
    FILE* f = fopen(file, "r");

    if (!f) {
        return false;
    }
    fclose(f);
    return true;
}

int main()
{
    char schedule_file[] = "single_node_boolean.sql single_node_char.sql single_node_name.sql single_node_varchar.sql";
    char** tests = NULL;
    tests = (char**)malloc(sizeof(char**));
    char* pcTemp = NULL;
    bool InsideWord = false;
    int num_tests = 0;

    for (pcTemp = schedule_file; *pcTemp != '\0'; pcTemp++) {
        if (*pcTemp == ' ') {
            *pcTemp = '\0';
            InsideWord = false;
        } else if (!InsideWord) {
            tests[num_tests] = pcTemp;
            num_tests++;
            InsideWord = true;
        }
    }

    int int_temp = 0;
     while (int_temp < num_tests) {
        file_exists(tests[int_temp]);
        int_temp++;
    }
}
3 回复
#2
lvhui1234562021-01-27 16:04
尝试过char二维数组,strcpy给赋值文件名,没有该问题,但字符串切割就出现崩溃,我想知道为什么,到底是什么原因导致fclose崩溃
#3
lvhui1234562021-01-27 17:35
问题已经找到了,是tests = (char**)malloc(sizeof(char**))申请的空间不够,导致tests[1]/tests[2]/tests[3]地址越界了。
改成tests = (char**)malloc(4 * sizeof(char**))就好了,但还有个疑问,就是为何当tests空间不够时,为何schedule_file包含三个文件又没有问题? 太奇怪了!
#4
lin51616782021-02-01 09:13
C语言 只保证正确的代码 得到预期的结果
不保证错误的代码得到预期的错误
1