跨范围访问堆栈变量时隐藏指针逻辑

时间:2015-08-13 10:38:10

标签: c++ pointers stack

我写了几行代码来愚弄指向堆栈变量的指针。这个想法最初非常简单但后来偶然发现了一种奇怪的行为......

这就是我想要做的事情:

  1. 打开一个范围,
  2. 声明并初始化一个int,
  3. 将其地址存储在全局变量中并关闭范围,
  4. 然后

    1. 打开一个新范围,
    2. 声明一个int并使用前一个指针初始化其值。
    3. 正如预期的那样,第二个作用域中的int保留了第一个int的值,但是当它通过全局指针(在3中初始化)进行更改时,它的值不会改变,尽管全局指针确实保持正确地址!

      我粘贴了下面的代码和输出。

      注意:是的,它很有趣,我不会在现实代码中使用这个hack ....我只是希望更深入地了解机器代码级别的内容。

          void main()
          {
              int * p, * q;
              {
                  int x = 11;
                  p = &x;
      
                  // Obvious check
                  cout << "@x= " << &x << endl;
                  cout << "p= " << p << endl;
                  cout << "x= " << x << endl;
                  cout << endl;
              }
              {
                  int y;
      
                  // Trying to alter y through previous x's address
                  *p = 666;
                  cout << "*p= " << *p << endl;
                  cout << "y= " << y << endl;
                  cout << endl;
      
                  // Trying to alter y through y's address
                  q = &y;
                  *q = 123;
                  cout << "@y= " << &y << endl;
                  cout << "q= " << q << endl;
                  cout << "y= " << y << endl;
                  cout << endl;
              }
      
              cout << (p==q ? "same" : "different!") << endl;
          }
      

      现在输出:

          @x= 0015FCEC
          p= 0015FCEC
          x= 11              ============> everything is going as planned :-)
      
          *p= 666            ============> the int pointed by p did change ...
          y= 11              ============> ... but y still holds the previous x's value.
      
          @y= 0015FCEC
          q= 0015FCEC        ============> And yet p and q point to the same int!
          y= 123
      
          different!         ============> Interestingly, p==q returns false.
      

0 个答案:

没有答案