Why does cout << &r give different output than cout << (void*)&r? - c++

This might be a stupid question, but I'm new to C++ so I'm still fooling around with the basics. Testing pointers, I bumped into something that didn't produce the output I expected.
When I ran the following:
char r ('m');
cout << r << endl;
cout << &r << endl;
cout << (void*)&r << endl;
I expected this:
m
0042FC0F
0042FC0F
..but I got this:
m
m╠╠╠╠ôNh│hⁿB
0042FC0F
I was thinking that perhaps since r is of type char, cout would interpret &r as a char* and [for some reason] output the pointer value - the bytes comprising the address of r - as a series of chars, but then why would the first one would be m, the content of the address pointed to, rather than the char representation of the first byte of the pointer address.. It was as if cout interprets &r as r but instead of just outputting 'm', it goes on to output more chars - interpreted from the byte values of the subsequent 11 memory addresses.. Why? And why 11?
I'm using MSVC++ (Visual Studio 2013) on 64 bit Win7.
Postscript: I got a lot of correct answers here (as expected, given the trivial nature of the question). Since I can only accept one, I made it the first one I saw. But thanks, everyone.
So to summarize and expand on the instinctive theories mentioned in my question:
Yes, cout does interpret &r as char*, but since char* is a 'special thing' in C++ that essentially means a null terminated string (rather than a pointer [to a single char]), cout will attempt to print out that string by outputting chars (interpreted from the byte contents of the memory address of r onwards) until it encounters '\0'. Which explains the 11 extra characters (it just coincidentally took 11 more bytes to hit that NUL).
And for completeness - the same code, but with int instead of char, performs as expected:
int s (3);
cout << s << endl;
cout << &s << endl;
cout << (void*)&s << endl;
Produces:
3
002AF940
002AF940

A char * is a special thing in C++, inherited from C. It is, in most circumstances, a C-style string. It is supposed to point to an array of chars, terminated with a 0 (a NUL character, '\0').
So it tries to print this, following on in to the memory after the 'm', looking for a terminating '\0'. This makes it print some random garbage. This is known as Undefined Behaviour.

There is an operator<< overload specifically for char* strings. This outputs the null-terminated string, not the address. Since the pointer you're passing this overload isn't a null-terminated string, you also get Undefined Behavior when operator<< runs past the end of the buffer.
Conversely, the void* overload will print the address.

Because operator<< is overloaded based on the data type.
If you give it a char, it assumes you want that character.
If you give it a void*, it assumes you want an address.
However, if you give it a char*, it takes that as a C-style string and attempts to output it as such. Since the original intent of C++ was "C with classes", handling of C-style strings was a necessity.
The reason you get all the rubbish at the end is simply because, despite your assertion to the compiler, it isn't actually a C-style string. Specifically, it is not guaranteed to have a string-terminating NUL character at the end so the output routines will just output whatever happens to be in memory after it.
This may work (if there's a NUL there), it may print gibberish (if there's a NUL nearby), or it may fall over spectacularly (if there's no NUL before it gets to memory it cannot read). It's not something you should rely on.

Because there's an overload of operator<< which takes a const char pointer as it's second argument and prints out a string. The overload that takes a void pointer prints only the address.

A char * is often - usually even - a pointer to a C-style null-terminated string (or a string literal) and is treated as such by ostreams. A void * by contrast unambiguously indicates a pointer value is required.

The output operator (operator<<()) is overloaded for char const* and void const*. When passing a char* the overload for char const* is a better match and chosen. This overload expects a pointer to the start of a null terminated string. You give it a pointer to an individual char, i.e., you get undefined behavior.
If you want to try with a well-defined example you can use
char s[] = { 'm', 0 };
std::cout << s[0] << '\n';
std::cout << &s[0] << '\n';
std::cout << static_cast<void*>(&s[0]) << '\n';

Related

Understanding C++ strings

I'm trying to understand how strings really work in C++ because I just got really confused after coming across an unexpected behavior.
Considering a string, I insert a character (not using append()) using [] operator:
string str;
str[0] = 'a';
Let's print the string:
cout << "str:" << str << endl;
I get NULL as output:
str:
Ok, let's try printing the only character in the string:
cout << "str[0]:" << str[0] << endl;
Output:
str[0]:a
Q1. What happened there? Why was a not printed in the first case?
Now, I do something that should throw a compilation error but it doesn't and my question is again, why.
str = 'ABC';
Q2. How's that not an incorrect semantic i.e. assigning a character (which is not really a character but essentially a string in single quotes) to a string?
Now, worse when I print the string, it always prints last character i.e C (I was expecting first character i.e. A):
cout << "str:" << str << endl;
Output:
str:C
Q3. Why was the last character printed, not first?
Considering a string, I insert a character (not using append()) using [] operator:
string str;
str[0] = 'a';
You did not insert a character. operator[](size_type pos) returns a reference to the - already existing - character at pos. If pos == size() then behaviour is undefined. Your string is empty, so size() == 0 and therefore str[0] has undefined behaviour.
Q1. What happened there? Why was a not printed in the first case?
The behaviour is undefined.
Now, I do something that should throw a compilation error but it doesn't and my question is again, why.
str = 'ABC';
Q2. How's that not an incorrect semantic i.e. assigning a character ... to a string?
Assigning a character to a string is not incorrect semantic. It sets the content of the string to that single character.
Q2. ... a character (which is not really a character but essentially a string in single quotes) ...
It is a multicharacter literal. The type of a multicharacter literal is int. If the compiler supports multicharacter literals, then the semantic is not incorrect.
There isn't an assignment operator for string that would accept an int. However, int is implicitly convertible to char, so the assignment operator that accepts a char is used after the conversion.
char cannot necessarily represent all the values that int can, so it is possible that the conversion overflows. If char is a signed type, then this overflow has undefined behaviour.
Q3. Why was the last character printed, not first?
The value of a multicharacter literal is implementation-defined. You'll need to consult the manual of your compiler to find out whether multicharacter literals are supported, and what value you should expect. Furthermore, you'll need to consider the fact that the char that the value is converted to probably cannot represent all values of int.
but I didn't get any warnings
Then consider getting a better compiler. This is what GCC warns:
warning: multi-character character constant [-Wmultichar]
str = 'ABC';
warning: overflow in implicit constant conversion [-Woverflow]
str[0] = 'a' should work with string just like it does with char str[] = "" (but it doesn't as we saw). Can you help me understand why [] operator has different behavior in dealing with array of characters than string?
Because that's how the standard has defined the behaviour and requirements of std::string.
char str[] = "";
Creates an array of size 1, consisting of the null terminator. This element of the array is like any other, and you can freely modify it:
str[0] = 'a';
This is well defined and OK. But now str no longer contains a null-terminated string, so trying to use it as such has undefined behaviour:
out << "str:" << str << endl; // oops, str is not a null terminated string
So, std::string has been designed such that you cannot mess with the final null terminator - as long as you obey the requirements of std::string. Not allowing touching the null terminator also allows the implementation to never allocate a memory buffer for an empty string. Not allocating memory may be faster than allocating memory, so this is a good thing.
You should take a look at http://en.cppreference.com/w/cpp/string/basic_string/operator_at. Namely, the portion about "If pos == size(), the behavior is undefined."
The following line creates an empty string:
string str;
so size() will return 0.
Your statement str string; str[0]='a' is undefined behaviour, though the reason for this differs between "before C++11" and "from C++11 on". Note that str is a non-const string. Before C++11 already a (read) access like str[pos] with pos == size() and str being a non-const string yields undefined behaviour. From C++11 on, a read-access would be permitted (yielding a reference to the '\0'-character. A modification, however, again is undefined in its behaviour.
So far to the Cpp reference regarding std::basic_string::operator_at.
But now let's explain the behaviour of a program similar to yours but with defined behaviour; (I'll use this then as analogy to describe the behaviour of your program):
string str = "bbbb";
const char* cstr = str.data();
printf("adress: %p; content:%s\n", cstr, cstr);
// yields "adress: 0x7fff5fbff5d9; content:bbbb"
str[0] = 'a';
const char* cstr2 = &str[0];
printf("adress: %p; content:%s\n", cstr2, cstr2);
// yields "adress: 0x7fff5fbff5d9; content:abbb"
cout << "str:" << str << endl;
// yields "str:abbb"
The program is almost self explanatory, but note that str.data()gives a pointer to the internal data buffer, and str.data() returns the same address as &str[0].
If we now change the same program to your setting with string str = "", then there does not even change to much in the behaviour (although this behaviour is undefined, not safe, not guaranteed, and may differ from compiler to compiler):
string str; // is the same as string str = ""
const char* cstr = str.data();
printf("adress: %p; content:%s\n", cstr, cstr);
// yields "adress: 0x7fff5fbff5c1; content:"
str[0] = 'a';
const char* cstr2 = &str[0];
printf("adress: %p; content:%s\n", cstr2, cstr2);
// yields "adress: 0x7fff5fbff5c1; content:a"
cout << "str:" << str << endl;
// yields "str:"
Note that str.data() returns the same address as &str[0] and that 'a' has actually been written to that address (if we have good luck, we do not access non-allocated memory, as an empty string is not guaranteed to have a buffer ready; maybe we have really good luck). So printing out str.data() actually gives you a (if we have additional luck that the character after 'a' is a string terminating char). Anyway, statement str[0]='a' does not increase string size, which is still 0, such that cout << str gives an empty string.
Hope this helps somehow.
string str;
Makes a string of length 0.
str[0] = 'a';
Sets the first element of the string to 'a'. Note that the length of the string is still 0. Also note there may not be space allocated to hold this 'a' and the program is broken at this point so further analysis is best guesses.
cout << "str:" << str << endl;
Prints the contents of the string. The string is length 0, so nothing prints.
cout << "str[0]:" << str[0] << endl;
reaches into undefined territories and tries to read back the previously stored 'a'. This won't work, and the result is undefined. In this case it gave the appearance of working, possibly the nastiest thing undefined behaviour can do.
str = 'ABC';
is not necessarily an error as there are multibyte characters out there, but this most likely will, but is not required to, result in a warning from the compiler as it's probably a mistake.
cout << "str:" << str << endl;
Your guess is as good as mine what the compiler will do since str = 'ABC'; was logically incorrect (although syntactically valid). The compiler seems to have truncated ABC to the last character much like putting 257 into a 8 bit integer may result in preserving only the least significant bit.

Weird output when using char double pointer

I get really weird output from the last cout statement, no idea what would be causing this:
char ex1_val = 'A';
char* ex1;
ex1 = &ex1_val;
cout << *ex1 << endl;
char** ex2;
ex2 = &ex1;
cout << *ex2 << endl;
Here's my output:
A
A����
ex2 is declared as char**, which means it's a pointer to a pointer to char.
When you print the contents of *ex2, you're dereferencing it once, so type of *ex2 is a pointer to char.
Effectively, the compiler assumes, that you want to print a C-style string, which is a NULL-terminated string. So it prints all bytes stored in memory, starting from A stored in ex1_val, followed by random values stored directly after that, until a NULL character is encoutered.
This is actually a very bad situation, as you never know when or if there's a NULL in memory. You might end up trying to access a memory area you're not allowed to use, which may result in crashing the application. This is an example of an undefined behaviour (UB).
To print out the actual contents of ex1_val via the ex2 pointer, you'd need to make it like this:
cout << **ex2 << endl;
where typeof(**ex2) is an actual char.
When you dereference ex2 (in *ex2) you get a pointer to a char (i.e. char*), and the operator<< overload to handle char* outputs it as a C-style zero-terminated string.
Since *ex2 doesn't point to a zero-terminated string, only a single character, you get undefined behavior.
You want to do cout << **ex2 << endl;
ex2, as you have declared it, as a pointer to a pointer to a character. Doing *ex2 only gets you the address of the pointer it is pointing to.

C++ char pointer

Why does the following happen?
char str[10]="Pointers";
char *ptr=str;
cout << str << "\n"; // Output : Pointers
int abc[2] = {0,1 };
int *ptr1 = abc;
cout <<ptr1 << "\n"; // But here the output is an address.
// Why are the two outputs different?
As others have said, the reason for the empty space is because you asked it to print out str[3], which contains a space character.
Your second question seems to be asking why there's a difference between printing a char* (it prints the string) and int* (it just prints the address). char* is treated as a special case, it's assumed to represent a C-style string; it prints all the characters starting at that address until a trailing null byte.
Other types of pointers might not be part of an array, and even if they were there's no way to know how long the array is, because there's no standard terminator. Since there's nothing better to do for them, printing them just prints the address value.
1) because str[3] is a space so char * ptr = str+3 points to a space character
2) The << operator is overloaded, the implementation is called depending on argument type:
a pointer to an int (int*) uses the default pointer implementation and outputs the formatted address
a pointer to a char (char*) is specialized, output is formated as a null terminated string from the value it points to. If you want to output the adress, you must cast it to void*
The empty space is actually Space character after "LAB". You print the space character between "LAB" and "No 5".
Your second question: You see address, because ptr1 is actually address (pointer):
int *ptr1;
If you want to see it's first member (0), you should print *ptr1

Weird output when printing char pointer from struct

Here is the code:
#include<iostream>
struct element{
char *ch;
int j;
element* next;
};
int main(){
char x='a';
element*e = new element;
e->ch= &x;
std::cout<<e->ch; // cout can print char* , in this case I think it's printing 4 bytes dereferenced
}
am I seeing some undefined behavior? 0_o. Can anyone help me what's going on?
You have to dereference the pointer to print the single char: std::cout << *e->ch << std::endl
Otherwise you are invoking the << overload for char *, which does something entirely different (it expects a pointer to a null-terminated array of characters).
Edit: In answer to your question about UB: The output operation performs an invalid pointer dereferencing (by assuming that e->ch points to a longer array of characters), which triggers the undefined behaviour.
It will print 'a' followed by the garbage until it find a terminating 0. You are confusing a char type (single character) with char* which is a C-style string which needs to be null-terminated.
Note that you might not actually see 'a' being printed out because it might be followed by a backspace character. As a matter of fact, if you compile this with g++ on Linux it will likely be followed by a backspace.
Is this a null question.
Strings in C and C++ end in a null characher. x is a character but not a string. You have tried to make it one.

address value of character pointers

//if the code is
char str[]="hello";
char *sptr=&str[2];
cout<<sptr;
//the output is not a hexadecimal value but llo
....why?
//also consider the following code
char array[]="hello world";
char array1[11];
int i=0;
while(array[i]!='\0')
{array1[i]=array[i];
i++;}
//if we print array1,it is printed as hello world, but it should have stopped when the space between hello and world is encountered.
The operator<< overload used by output streams is overloaded for const char* so that you can output string literals and C strings more naturally.
If you want to print the address, you can cast the pointer to const void*:
std::cout << static_cast<const void*>(sptr);
In your second problem, \0 is the null terminator character: it is used to terminate the string. array actually contains "hello world\0", so the loop doesn't stop until it reaches the end of the string. The character between hello and world is the space character (presumably): ' '.
When you print a char*, it's printed as a string.
'\0' is not ' '
Regarding your first question:
By default, a char is interpreted as its textual representation trough a call to std::cout.
If you want to output the hexadecimal representation of your character, use the following code:
std::cout << std::hex << static_cast<int>(c);
Where c is your character.
In your code:
cout<<sptr;
sptr is a pointer to a char, not a char so std::cout displays it as a C-string.
Regarding your second question:
A space is the ASCII character 32, not 0. Thus your test just checks for the ending null character for its copy.
With regards to cout, there is a special overload for writing const char * (and char *) to streams that will print the contents rather than the pointer.
With regards to array1, actually there is nothing wrong with making it size 11 as you do not copy the null byte into it. The issue comes though when you try printing it, as it will try to print until it finds a 0 byte and that means reading off the end of the array.
As it stands the compiler may well pad out a few bytes because the next thing that follows is an int so it is likely to align it. What is actually in that one byte of padding could be anything though, not necessarily a zero character.
The next few characters it is likely to meet will be the int itself, and depending on the endian-ness the zero byte will be either the first or second.
It is technically undefined behaviour though.