堆栈地址和堆地址之间的关系?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆栈地址和堆地址之间的关系?相关的知识,希望对你有一定的参考价值。

基本上,我们被要求预测以下程序的输出。我有些困惑,我已经在代码本身的注释中指出了这一点:

#include <stdio.h>
#include <stdlib.h>

void foo ( int * z) ;

int main () {

  int x = 10;
  int * y = (int*) malloc(sizeof(int));
  *y = x;
  printf("x = %d	*y = %d
", x, *y); //This should print x = 10, *y = 10

  if (&x > y ) { //I am confused about this particular scenario, as far as I know we are not able to guarantee when the heap addresses are higher or lower than stack addresses, I believe this differs from system to system?
    printf ("XXX
"); //So there is no way of knowing which if statement we go to right?
  }
  else {
    printf ("YYY
");
  }
  foo(&x);
  foo(y);

  if (y!=0) free(y);
  return 0;
}

void foo ( int * z) {
  int w = 5;
  if (&w > z ) { //Again when we come here is there any way for us to know exactly which if statement we will go into? Considering that we don't really know how the system will allocate memory?
    printf ("WWW
");
  }
  else {
    printf ("ZZZ
");
  }
}

任何帮助将不胜感激!谢谢!

答案

怎么样:

以上是关于堆栈地址和堆地址之间的关系?的主要内容,如果未能解决你的问题,请参考以下文章

C++中栈和堆的地址

进程和线程和协程之间的关系

内核空间和内核堆栈之间的关系是什么?

堆栈内存和堆内存之间的区别[重复]

Swift 栈和堆的理解

如何在堆栈和堆对象之间转换