I have such a function that reads all the contents of the data file.txt, which contains variables of the given structure type, in the format DD mm yyyy. this is the function
void readFromFile(struct data *element){
FILE *data_file;
data_file = fopen("D:\\univer\\sem2\\tehProg\\struct_and_files\\struct.txt","rw");
if(data_file == NULL){
fprintf(stderr, "Nu se poate de deschis fisierul\n");
return;
}
char line[100];
while (fgets(line, sizeof line, data_file))
{
int y, m, d;
if (sscanf(line, "%d %d %d", &d,&m,&y))
{
element[n].d = d;
element[n].m = m;
element[n].y = y;
n;
}
}
fclose(data_file);
}
For this, I assign memory to the variable DD1, and transmit it as a paramatron in my function, from main.
struct data *dd1 = malloc(sizeof *dd1);
readFromFile(dd1);
displayN(dd1);
struct data maximum = checkMax(dd1);
struct data minimum = checkMin(dd1);
printf("\n Data maxima %d %d %d",maximum.d,maximum.m,maximum.y);
printf("\n Data minima %d %d %d", minimum.d,minimum.m,minimum.y);
printf("\n Nr de ani bisecti : %d ", checkLeapYear(maximum,minimum));
free(dd1);
Everything works, but I get this error code (-1073741819 (0xC0000005)) in the console. What could be the cause?
CodePudding user response:
struct data *dd1 = malloc(sizeof *dd1);
allocates room for a single struct. Yet in the function, you use this as if it was an array of structs:element[n]
. So you access the array wildly out of bounds. Hence the access violation reported.In case you wish to use
realloc
inside the function to solve this, you need to either pass the struct array as pointer-to-pointer or return a pointer to it from the function.if (sscanf(line, "%d %d %d", &d,&m,&y))
is wrong sincesscanf
will either return 1 to 3 in case 1-3 numbers were read successfully orEOF
. It will not return NULL likefgets
. Also you probably shouldn't have spaces in thesscanf
call.n
ought to be a local variable inside the function, not an icky global.