我认为指针有麻烦

时间:2019-12-27 15:30:19

标签: c pointers

因此,我正在尝试用C语言为我的大学做一份实习! 我的代码可以正常编译,但由于以下原因而在运行时崩溃: “在EceProj.exe中的0x00007FFAF517D751(ucrtbased.dll)引发异常:0xC0000005:访问冲突读取位置0xFFFFFFFFFFFFFFFFFF。 谁能帮帮我吗。 以下是我的代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct Log {
    char*   field1;
    char*   field2;
    int     field3;
    float   field4;
    float   field5;
    float   field6;
    float   field7;
    float   field8;
    float   field9;
}log_t, *plog;

FILE* OpenFile(const char* path) 
{
    FILE* file = NULL;
    file = fopen(path, "r");
    if (file == NULL)
        printf("File cant be opened\n");
    else
        printf("File is opened\n");
    return file;
}

log_t CreateLog(FILE* file)
{
    plog log = (plog)malloc(sizeof(plog));
    fscanf(file, "%s", log->field1);
    fscanf(file, "%s", log->field2);
    fscanf(file, "%d", &(log->field3));
    fscanf(file, "%f", &(log->field4));
    fscanf(file, "%f", &(log->field5));
    fscanf(file, "%f", &(log->field6));
    fscanf(file, "%f", &(log->field7));
    fscanf(file, "%f", &(log->field8));
    fscanf(file, "%f", &(log->field9));
    return *log;
}

void PrintLog(log_t log)
{
    printf("%s", log.field1);
}

int main()
{
    FILE* file;
    file = OpenFile("DataMeteoE4.txt");
    log_t log = CreateLog(file);
    PrintLog(log);
    fclose(file);
    return 0;
}

我打开的文件是带有温度和压力等的一些日志。 这些是文件的内容。

2015-07-22 09:00:00 1346137 13.03 25.13 6.474 3.805 0.832 25.84
2015-07-22 09:01:00 1346138 13.03 25.15 6.5 3.84 0.834 25.89
2015-07-22 09:02:00 1346139 13.03 25.19 6.477 3.851 0.836 26.02
2015-07-22 09:03:00 1346140 13.03 25.22 6.493 3.879 0.841 26.07
2015-07-22 09:04:00 1346141 13.02 25.25 6.516 3.91 0.846 26.01

1 个答案:

答案 0 :(得分:1)

对于初学者来说,此功能

log_t CreateLog(FILE* file)
{
    plog log = (plog)malloc(sizeof(plog));
    fscanf(file, "%s", log->field1);
    fscanf(file, "%s", log->field2);
    fscanf(file, "%d", &(log->field3));
    fscanf(file, "%f", &(log->field4));
    fscanf(file, "%f", &(log->field5));
    fscanf(file, "%f", &(log->field6));
    fscanf(file, "%f", &(log->field7));
    fscanf(file, "%f", &(log->field8));
    fscanf(file, "%f", &(log->field9));
    return *log;
}

存在内存泄漏,因为退出函数后,分配给内存的地址丢失了。

您正在从文件中读取指针field1。它的值对于程序的当前状态可能无效。所以这个功能

void PrintLog(log_t log)
{
    printf("%s", log.field1);
}

调用未定义的行为。

似乎数据成员field1field2应该是字符数组,而不是指针。

例如

typedef struct Log {
    char   field1[11];
    char   field2[9];
    //...