C++ 如何避免“无法读取内存”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25893840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:28:13  来源:igfitidea点击:

How to avoid "unable to read memory"

c++

提问by Thomas Andrees

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.) cand in debbuger this value is called

有时当我想阅读(例如)c并且在调试器中这个值被称为

'unable to read memory'

'无法读取内存'

Then my program crashed.

然后我的程序崩溃了。

And now, how to check that value is readable or not ?

现在,如何检查该值是否可读?

Best Regards.

此致。

回答by Mike Seymour

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 nullif you don't want it to point to anything. You mustn't dereference it, but it is possible to test for a null pointer:

如果您不希望指针指向任何内容,您可以将指针设为null。您不能取消引用它,但可以测试空指针:

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