1

I'm trying to learn about stack and heap at c++ and just started to print tests to learn how it's work.

I wrote this code:

`#include <iostream>

 using namespace std;

 int main (){

 int a;
 int b;
 int *c;
 int *c2;
 int *d{new int};

 cout << &a << "   a= " << a << endl;
 cout << &b << "   b= " << b << endl;
 cout << &c << "   c= " << c << endl;
 cout << &c2 << "  c2= " << c2 << endl;
 cout << &d << "   d= " << d << endl;

 delete d;

 return 0;

 }

the output is:

0x7ffefad88d00 a= 124

0x7ffefad88d04 b= 0

0x7ffefad88d08 c= 0

0x7ffefad88d10 c2= 0x400b20

0x7ffefad88d18 d= 0xec9c20

There are 3 things I do not understand:

  1. why a value is 124?
  2. why c value is 0 and not a pointer like c2 that have the same syntax?
  3. why c size is just 2 byts and not 4?
trincot
  • 317,000
  • 35
  • 244
  • 286
adi319
  • 101
  • 4

2 Answers2

2

a, b, c, d and the value of *d are uninitialized, reading them is undefined behavior. Anything can happen, nobody can predict the value of those variables. See this question for more information.

About the printout of the pointers, many implementations trim leading 0s. See this question. If I try to print out the values of pointers in Visual Studio 2015, I get the leading zeros.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
1

why a value is 124?

a is uninitialized, hence reading it will give you unpredictable value. Reading uninitialized non-static local variable is UB. But, uninitialized global and static variables are initialized with 0 at compile time and reading them is fine.

why c value is 0 and not a pointer like c2 that have the same syntax?

c is also uninitialized, so what it points to is also undefined as mentioned above. It is a pointer like c2, but it points to NULL (which is 0).

why c size is just 2 bytes and not 4?

c size of a pointer is architecture and/or compiler dependent. In this case c occupied 8 bytes. subtract the address of c from the address of c2.

0x7ffefad88d10 - 0x7ffefad88d08 = 0x000000000008 these are hexadecimal values not decimal.

So, c is actually a pointer like c2 and occupies same space in the memory.

army007
  • 551
  • 4
  • 20