So im trying to make an excersice for my university in C language! My code compiles fine but it crashes in runtime by the exception: "Exception thrown at 0x00007FFAF517D751 (ucrtbased.dll) in EceProj.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF." Can anyone please help me. Below is my code
#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;
}
The file that i open is this one with some logs with temperature and preasure etc.. These are the contents of the file..
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
For starters this function
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;
}
has a memory leak because the address to the allocated memory is lost after exiting the function.
You are reading the pointer field1 from a file. Its value can be invalid for the current state of the program. So this function
void PrintLog(log_t log)
{
printf("%s", log.field1);
}
invokes undefined behavior.
It seems the data members field1
and field2
shall be character arrays instead of pointers.
For example
typedef struct Log {
char field1[11];
char field2[9];
//...
User contributions licensed under CC BY-SA 3.0