![](/img/trans.png)
[英]Why does std::cout of a dereferenced pointer to pointer cause -fsanitize=address to complain?
[英]What could cause writing a pointer address to std::cout to crash?
每当我将特定的指针地址输出到std::cout
,我都会崩溃:
bool MyClass::foo() const
{
std::cout << "this prints fine" << std::endl << std::flush;
std::cout << d << std::endl << std::flush; // crash!
return true;
}
其中d
是该类的指针成员,即:
class MyClass {
// ...
private:
MyClassPrivate* d;
};
是什么导致应用程序崩溃? 即使它是NULL指针还是初始化的指针,它仍应打印出(可能是无效的)地址,对吗?
如果有所不同,则在调试模式下编译应用程序。 函数foo
未标记为内联。
背景:我正在尝试查找外部应用程序过程中的错误。 仅当另一个应用程序向该进程发送快速启动命令时才引起该错误。 我正在使用std::cout
跟踪外部进程的执行。
如果this
不是有效的指针,则对成员字段的任何访问都可能导致访问冲突。 在无效指针上调用的非虚拟方法可以正常工作,直到它们尝试访问字段为止,因为调用本身不需要取消引用this
。
例如,这种情况将按照您的描述大致崩溃:
MyClass* instance = nullptr; // or NULL if you're not using C++11
instance->foo(); // will crash when `foo` tries to access `this->d`
可能会取消引用指针的operator<<(ostream &, MyClassPrivate*)
的重载。 例如,如果MyClassPrivate
确实是char
那么肯定存在。
尝试std::cout << (void*)d;
,看看是否有所作为。 如果不是这样,zneak的答案似乎是合理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.