Ok I gave up so I did a workaround. I wrote field by field, then malloc()
ing the Polygon, then reading field by field and populate Polygon.
Reading linked list from file in C
-
19-09-2022 - |
Вопрос
I'm supposed to read this linked list of pointers from a file.
Problem is that whenever fread()
is called it changes not only the pointer *p, but *poly aswell, then it causes addNVertex()
to crash the program. Read polygon method:
Polygon* readPolygon(FILE *file){
Polygon *poly=initPoly();
Point p;
int numofvertice,i;
fread(&numofvertice,sizeof(int),1,file);
for(i=0;i<numofvertice;i++){
fread(&p,sizeof(Point),1,file);
addNVertex(poly,&p,i+1);
}
return poly;
}
It is a binary file looking something like this:
int,point,point...,int,point,point...
The int represents the number of points to add to the polygon.
An example: if *poly was 0x8000 before the 2nd fread()
(after initPoly()
) , after the second fread()
it changes to other value even though I read the data to &p???
I've been debugging this for the past hour still nothing comes up...
Решение 4
Другие советы
This is wrong:
Point *p=(Point*)malloc(sizeof(Point));
...
fread(&p,sizeof(Point),1,file);
The call to fread
reads in data from the file and stores it at the memory occupied by the pointer p
. p
is a local variable on the stack and likely has a size of 4 or 8 bytes, depending on your program's bitness. But you're reading in sizeof(Point)
bytes; if Point
is larger than a pointer, you're smashing the stack with a buffer overrun.
You really meant to write this:
// V-- No "&" here
fread(p,sizeof(Point),1,file);
This reads the file data into the memory pointed to be p
, not the pointer object p
itself. Since you actually have sizeof(Point)
bytes worth of data there, this does not write out of bounds.
You're also failing to free the memory you've allocated here, but that memory leak is an entirely separate issue.
p
is declared as a pointer. Thus using &p
in the fread
call will not read into the memory where p
points to, but change the p
pointer itself. It causes both a memory overflow trashing your numofvertice
and i
variables (and possibly more) and store an invalid memory address in p
. Just fread
into p
and not into &p
:
fread(p, sizeof(Point), 1, file);
Instead of using dynamic memory allocation for p
, you can just use stack variable
Point p;
Then the second fread will be valid
fread(&p,sizeof(Point),1,file);
You may also need to change to
addNVertex(poly, &p, i+1);