8

Why does

#include <iostream>
using namespace std;

int main() {
  cout << (char*)0x10 << endl; 
}

segfault, but

#include <iostream>
using namespace std;

int main() {
  cout << (void*)0x10 << endl; 
}

seems to work just fine?

abeln
  • 3,749
  • 2
  • 22
  • 31

3 Answers3

10

Because

cout::operator <<(void*) 

prints a memory address, and

cout::operator <<(char*)

prints a null-terminated character array, and you run into undefined behaviour when you attempt to read the char array from 0x10.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
4

The ostream::operator<< is overloaded, there is a version for char* which interprets the given pointer as a null-terminated string.

Zeta
  • 103,620
  • 13
  • 194
  • 236
3

There's a special overload for << with char*, so that C-style strings can be output easily.

Thus

cout << (char*)0x10 << endl; 

tries to print out the string located at (char*)0x10 which is not memory it's supposed to look at.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431