How to avoid "memory readability"

I have a structure:

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 example) c

and in debbuger this value is called

'memory cannot be read

Then my program crashed.

Now, how do you check if a value is readable or not?

Regards.

+3


source to share


1 answer


You haven't initialized a pointer to anything, so it's not valid. You cannot, in general, check if a pointer is pointing to a valid object. It's up to you to make sure this is the case; eg:

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 the pointer null if you don't want it to point to anything. You shouldn't play it, but you can check 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 be careful that this will not help in situations where a pointer might be invalid but not null; perhaps because it was not initialized or because it pointed to an object that was destroyed.

In general, avoid pointers unless you really need them; and be careful not to use invalid pointers when you do this. If you just want an object, just use an object:

a b(1,2);     // an object
cout << b.a;  // OK: b is a valid object

      

+4


source







All Articles