Jack
7/16/2011 8:24:00 PM
On Sat, 16 Jul 2011 10:25:41 +0100, Dr Nick wrote:
> Jack <spamtrap@trashcan.invalid> writes:
>
>> On Fri, 15 Jul 2011 21:43:53 +0000, John Gordon wrote:
>>> In <ivq9i7$841$1@speranza.aioe.org> Jack <spamtrap@trashcan.invalid>
>>> writes:
>>>
>>>> I got a strange problem with Fread:
>>>
>>>> It crashes my program from time to time, in one of its internal
>>>> memcpy calls.
>>>
>>> When things like this happen it is nearly always because of a memory
>>> corruption bug elsewhere in your program, not because of a bug in a
>>> library function like fread().
>>>
>>> C is, unfortunately, a fragile language. If you copy more to a buffer
>>> than it can hold, or call free() on a bad value, or call free() twice
>>> on the same value, you've just corrupted the memory space of your
>>> program and anything can happen from that point onward, including
>>> crashes in library functions such as fread().
>>>
>>> If your program is a simple one, go over it again and try to identify
>>> any areas where you might have committed the above errors. If it's a
>>> complex program, you might use a memory analyzer such as efence or
>>> valgrind.
>>
>> Yes...
>> Actually, I think it's a memory error somewhere that causes really
>> indirectly this bug.
>> But I find it strange that even a memory error makes a fread with
>> proper parameters ( I do check this ) fail.
>
> Somewhere the library and the operating system have to store things like
> the details of the underlying file, the position in it etc. When you
> trample over memory you can overwrite this.
>
> In particular, many systems get the buffers for the stdio streams from
> the same memory pool as you get with malloc. So do something wrong with
> a block you've got from malloc and you can really mess the streams up.
>
> And vice versa. I once managed to get malloc to return "null" by
> previously fclosing the same file pointer twice.
>
>> I've heard somewhere one can play with the file buffer, so I tried it,
>> and put MY file buffer, with the Setbuff() function. And it didn't
>> crash anymore, but the read couldn't read all the files. Some bytes in
>> the middle were missing (I think it is when I resume the reading, after
>> having processed the first part)...
>
> That's not incompatible with what I wrote above.
Thanks for your help. I think I've now found a solution.
After the file is first Fopen'd, I make a backup of the internal buffers.
fp=Fopen(...);
FILE fback;
memcpy(&fback,fp,sizeof(FILE));
then before the fread I restore this buffer,
memcpy(fp,&fback,sizeof(FILE));
Fread(...,fp);
Now there is no segmentation fault, job done.