0

I am using fseek and fread on a FILE * like this:

void CAudioDataItem::finalizeItem_ReadEncodedBytesWithoutDecoding(FILE* uFile, CLog* uLog, double& uTimeReadEncodedBytes)
{
    //t.start();
    fseek(uFile, iFirstByteToRead, SEEK_SET);
    fread(&m_EncodedBytes[0], sizeof(unsigned char), m_lLenEncodedBytes, uFile);
    //t.stop();

However, it doesn't work, the bytes are all 0.

I suspect that somewhere in my app, the FILE pointer gets invalid or something else becomes wrong with this pointer.

How could I check if this file handle is still valid and "usable"?

Here is a screenshot:

enter image description here


Here is a screenshot of a situation where it still works. As one can see, the _Placeholder is different. What does this _Placeholder mean?

enter image description here

Enlico
  • 23,259
  • 6
  • 48
  • 102
tmighty
  • 10,734
  • 21
  • 104
  • 218

1 Answers1

3

If the question is on C++ as one of the tags imply,

There's typically no way to tell if the pointer dangles, i.e., points to memory that no longer holds the object the pointer is supposed to point to.

from Effective Modern C++, in the introduction to Chapter 4 - Smart Pointers, page 117.

If it's on C, then from the comments we know the same point holds for C.

As regards _Placeholder=0x00000000 when it doesn't work vs _Placeholder=0x1bc715bf when it works, I'm not sure why the numbers (which are memory addresses, I believe) are those that you see; maybe _Placeholder=0x00000000 means that something in the program has set the pointer to nullptr, but the point is that once that (or something else which invalidates the pointer) has happened, you can't do anything to query it.

The only way to go about this is to surrender to the evidence that the program has a bug that results in undefined behavior and try to debug it.

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • Same thing applies to C. – HolyBlackCat Aug 20 '21 at 14:46
  • @Enlico I have added yet another screenshot where it still works. As one can see, the "placeholder" is different. What does this placeholder mean? – tmighty Aug 20 '21 at 14:56
  • @tmighty it means there isn't a meaningful name for the (first? only?) data member of `FILE` objects – Caleth Aug 20 '21 at 15:06
  • @tmighty what `placeholder` means isn't important. It's is an internal implementation detail. It's probably an [opaque pointer](https://en.wikipedia.org/wiki/Opaque_pointer), but it could be just about anything else. You're much better served by tracking down and killing whatever bug is causing you grief. Perhaps you can put an On Memory Change breakpoint on it's location and see if it helps you find when/where it got changed. – user4581301 Aug 20 '21 at 15:44