Reputation:
Im looking for a better understanding of the following 3 examples.
This is my questions to the following code examples.
Lastly how do i output the adress of the memory location of where a char variable is saved?
Ex. 1
main(void)
{
int a = 1;
cout << &a;
}
Outputs the memory adress ex. 0x7fff4241b7b4
Ex 2.
main(void)
{
char a = 'a';
cout << &a;
}
Outputs the char a. ex. a
Ex. 3.
main(void)
{
char a = 'a';
char *b = &a;
cout << &a;
}
Outputs a��:��
Upvotes: 1
Views: 89
Reputation: 134028
The first pointer matches the operator<<(const void*)
that outputs the pointer value; the second and third match operator<<(const char*)
that will output a null-terminated string.
char a
is a value on stack, so it is totally undefined whether the bytes after the first byte are null or not, luckily in the middle case it is followed by a null byte, but in the 3rd case some bytes following are not null bytes and you get broken UTF-8 characters. The fact that you are setting a pointer does not affect the running of the program, but the stack frame is set up differently, and GCC for example emits movb $97, -9(%rbp)
assembler opcode to set the byte on stack, putting the char in a non-aligned address. The stack layout on my computer is this (64 bit)
| x | x | x | x | x | x | a | b | b | b | b | b | b | b | b |
^
RPB
Thus a
is then on stack directly followed by the b pointer value; the garbage I see when running on my machine comes from this pointer value. In fact if I change the ex 3 into
#include <iostream>
int main(void)
{
char a = 'a';
long b = 0x68676665646362l;
std::cout << &a;
}
I get output
abcdefgh
Of course this is an example of undefined behaviour; compile using another compiler, run on another platform and the program can according to standards as well crash, print the complete text of Hamlet or achieve self-awareness.
Upvotes: 6
Reputation: 409404
The second and third examples outputs the pointer as a string. But as the actual data is only a single character with no string terminator, you get undefined behavior as the output operator continues to output beyond the actual data in its search for the terminator.
If you want to print the actual pointer, then you have to cast the pointer:
std::cout << static_cast<void*>(&a) << '\n';
Upvotes: 2