c++ - Different content of &a -


im looking better understanding of following 3 examples.

this questions following code examples.

  • ex. 1. example makes sense, outputs adress of int stored.
  • ex. 2. makes little less sense for. think because char points char?
  • ex. 3. confuses me. in output first char output on stored in char. appending chars , why appear after saving &a char pointer?

lastly how output adress of memory location of char variable saved?

ex. 1

main(void)  {   int = 1;   cout << &a; } 

outputs memory adress ex. 0x7fff4241b7b4

ex 2.

main(void)  {   char = 'a';   cout << &a; } 

outputs char a. ex. a

ex. 3.

main(void)  {   char = 'a';   char *b = &a;   cout << &a; } 

outputs a��:��

the first pointer matches operator<<(const void*) outputs pointer value; second , third match operator<<(const char*) output null-terminated string.

char a value on stack, totally undefined whether bytes after first byte null or not, luckily in middle case followed null byte, in 3rd case bytes following not null bytes , broken utf-8 characters. fact setting pointer not affect running of program, stack frame set differently, , gcc example emits movb $97, -9(%rbp) assembler opcode set byte on stack, putting char in non-aligned address. stack layout on computer (64 bit)

| x | x | x | x | x | x | | b | b | b | b | b | b | b | b |                                                             ^                                                            rpb 

thus a on stack directly followed b pointer value; garbage see when running on machine comes pointer value. in fact if change ex 3

#include <iostream>  int main(void)  {     char = 'a';     long b = 0x68676665646362l;     std::cout << &a; } 

i output

abcdefgh 

of course example of undefined behaviour; compile using compiler, run on platform , program can according standards crash, print complete text of hamlet or achieve self-awareness.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo