Reputation: 783
I have the following method:
17 //returns size in bytes of binary file stream
18 //leaves the file at original position
19 long getFileSize(FILE * fp)
20 {
21 long pos = -1;
22 fpos_t *curPos;
23 if(fgetpos(fp, curPos) == 0)
24 {
25 fseek(fp, 0L, SEEK_END);
26 pos = ftell(fp);
27 fsetpos(fp, curPos);
28 }
29
30 return pos;
31 }
This will compile and work but compiler will give me a warning because curPos is not a initialized variable.
If I change that line to (which the compiler recommends)
22 fpos_t *curPos = NULL;
I receive a seg fault.
Why is this the case?
Upvotes: 0
Views: 295
Reputation: 2953
You haven't allocated curPos
.
So either allocate it on the heap (and be sure to free it later!)
fpos_t *curPos = malloc(sizeof(fpos_t));
Or on the stack
fpos_t curPos;
In case you allocate it on the stack you need to pass the reference to fgetpos
:
fgetpos(fp, &curPos)
Upvotes: 5
Reputation: 49893
curPos
needs to point to a fpos_t
object, so fgetpos
has a place to store the position.
Upvotes: 0
Reputation: 12214
You declared curPos
as a pointer (fpos_t *
), but never filled in the address where the data is to be found. That is why you get a segmentation fault when you try to store a value in the location indicated by the address (when you changed it to fpos_t *curPos = NULL;
)
As I look at the signature for fgetpos()
, I realize that what you want is to declare an fpos_t
and pass the address of the storage you have allocated so that fgetpos()
will write the value.
fpos_t curPos;
fgetpos(fp, &curPos);
Upvotes: 1