为什么
#include <iostream>
using namespace std;
int main() {
cout << (char*)0x10 << endl;
}segfault,但是
#include <iostream>
using namespace std;
int main() {
cout << (void*)0x10 << endl;
}看起来还不错吧?
发布于 2012-08-01 06:08:38
因为
cout::operator <<(void*) 打印内存地址,然后
cout::operator <<(char*)打印以null结尾的字符数组,并且在尝试从0x10读取char数组时遇到未定义的行为。
发布于 2012-08-01 06:09:36
ostream::operator<<是重载的,则有一个version for char*将给定的指针解释为以null结尾的字符串。
发布于 2012-08-01 06:09:00
char*为<<提供了一个特殊的重载,因此可以轻松地输出C样式的字符串。
因此
cout << (char*)0x10 << endl; 尝试打印位于(char*)0x10的字符串,该字符串不是它应该查看的内存。
https://stackoverflow.com/questions/11749725
复制相似问题