I have a struct:
struct a {
a(){};
a(int one,int two): a(one),b(two){};
int a;
int b;
int c;
}
a * b;
cout << b->c;
And sometimes when i want to read (for ex.) c
and in debbuger this value is called
'unable to read memory'
Then my program crashed.
And now, how to check that value is readable or not ?
Best Regards.
You haven't initialised the pointer to point to anything, so it's invalid. You can't, in general, test whether a pointer points to a valid object. It's up to you to make sure it does; for example:
a obj(1,2); // an object
a * b = &obj; // a pointer, pointing to obj;
cout << b->a; // OK: b points to a valid object
You can make a pointer null if you don't want it to point to anything. You mustn't dereference it, but it is possible to test for a null pointer:
a * b = nullptr; // or 0, in ancient dialects
if (b) cout << b->a; // OK: test prevents dereferencing
cout << b->a; // ERROR: b is null
But beware that this doesn't help in situations where a pointer might be invalid but not null; perhaps because it wasn't initialised, or because it pointed to an object that has been destroyed.
In general, avoid pointers except when you actually need them; and be careful not to use invalid pointers when you do. If you just want an object, then just use an object:
a b(1,2); // an object
cout << b.a; // OK: b is a valid object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With