Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a pointer with <iostream> [duplicate]

Tags:

c++

iostream

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?

like image 715
abeln Avatar asked Jul 31 '12 22:07

abeln


3 Answers

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.

like image 157
Luchian Grigore Avatar answered Nov 02 '22 12:11

Luchian Grigore


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

like image 4
Zeta Avatar answered Nov 02 '22 13:11

Zeta


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.

like image 3
Daniel Fischer Avatar answered Nov 02 '22 14:11

Daniel Fischer