I have a code where I use a pointer to access some datablock. Now in some rare cases, some members of the datablock are empty and as a result the pointer becomes dangling. Infact when I print out the address of the pointer, I get something like,
address = c0d6940
address = c19d088
address = 1
Crashes with segmentation fault when trying to do something with the pointer, which works before this line.

If I try to print out in decimal,
address = 201420752
address = 203774072
address = -131137536
and the same thing.

Now the usual advice I am getting is, to avoid this type of usage. But sadly, the framework I use dictate that I use this type of data access methods. So my question is, is there a way where I can "check" if the pointer is invalid (checking the pointer for not equal to NULL did not work, obviously) before doing any operation with it? Like somehow checking if the address is not something out of sync?

Thanks so much.:)

Unless you have a reliable way of setting
ptr = NULL;
at the moment the associated data is released, then no there isn't a way to work this out.

It could even be worse, your dangling pointer might end up pointing to another data instance if the same memory is reallocated for the same purpose later on in the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.