3

After printing a pointer to an int, I print a pointer to a char:

#include <iostream>

using namespace std;

int main() {

    int i;
    cout << "&i: " << &i << endl;

    char q = 'q';
    cout << "&q: " << &q << endl;

    return 0;

}

I get the following output as expected:

&i: 0xffffcc0c
&q: q

However, if I comment out cout << "&i: " << &i << endl;, and run the program again, I get the following unexplained output:

&q: q����

Does anyone know why this is happening?

If it has to do with operator<< inserting into the stream until it finds a null character, then why do I get the expected output when I include cout << "&i: " << &i << endl;?

NOTE: I am not expecting to get the address of q from cout. I am expecting to get the C string pointed to by &q. What bugs me is how the output just prints the 'q' if I include the line cout << "&i: " << &i << endl; beforehand. However, if I comment that line out, there is garbage data in the output. Why is there not garbage data in my output when I include the line cout << "&i: " << &i << endl;?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Daniel Gilbert
  • 133
  • 1
  • 7
  • 1
    @iammilind Not a duplicate. I am not expecting an address but a C string. However, I think you answered my question: "It's worth noting that printing a non NUL terminated c_str is a **undefined behavior**. Which happens in your case. That's why cout sequences also makes a difference in your compiler. It may or may not make such difference in my compiler." Thanks! – Daniel Gilbert Jan 15 '17 at 06:20

1 Answers1

2

The bit &q thinks it is a string.

Therefore will print up to the null character. hence the extra output

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • Then why don't I get extra output when I include the line `cout << "&i: " << &i << endl;` beforehand? – Daniel Gilbert Jan 15 '17 at 06:03
  • Because `&i` is an integer pointer - and treated differently – Ed Heal Jan 15 '17 at 06:05
  • 1
    @Daniel It's worth noting that printing a non NUL terminated `c_str` is a **undefined behavior**. Which happens in your case. That's why `cout` sequences also makes a difference in your compiler. It may or may not make such difference in my compiler. – iammilind Jan 15 '17 at 06:06
  • 1
    @DanielGilbert, If you mean the `&q` output changes depending on the other line being present, it's because printing the string starting at `&q` is going beyond the single character of memory you own, which is undefined behaviour. You can't safely rely on any particular behaviour. – chris Jan 15 '17 at 06:06
  • @iammilind - `std::string` is not involved - C strings (or lack of) are – Ed Heal Jan 15 '17 at 06:07