Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "unable to read memory"

Tags:

c++

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.

like image 274
Thomas Andrees Avatar asked Sep 17 '14 14:09

Thomas Andrees


1 Answers

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
like image 86
Mike Seymour Avatar answered Sep 21 '22 02:09

Mike Seymour