即使没有传递指针,线程中的所有函数都可以访问动态分配的内存(堆),还是函数的本地函数?

1 c heap memory-management dynamic

我有一个非常基本的问题,需要帮助.我试图了解动态分配的内存(在堆上)的范围.

#include <stdio.h>
#include <malloc.h>

//-----Struct def-------
struct node {
        int x;
        int y;
};

//------GLOBAL DATA------

//-----FUNC DEFINITION----
void funct(){
  t->x = 5; //**can I access 't' allocated on heap in main over here ?**
  t->y = 6; //**can I access 't' allocated on heap in main over here ?**
  printf ("int x = %d\n", t->x);
  printf ("int y = %d\n", t->y);
  return;
}

//-----MAIN FUNCTION------
int main(void){
      struct node * t = NULL;// and what difference will it make if I define 
                                 //it outside main() instead- as a global pointer variable
          t = (struct node *) malloc (sizeof(struct node));
      t->x = 7;
      t->y = 12;
      printf ("int x = %d\n", t->x);
      printf ("int y = %d\n", t->y);

    funct(); // FUNCTION CALLED**
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我可以访问结构tfunct(),即使分配内存在main()不经过论证(指针tfunction funct) -因为堆是共同的主题?将有什么关系,如果我定义struct node * t = NULL之外main()的全局变量,有什么错呢?

小智 8

当您使用malloc()时,可以在代码中的任何位置访问由此返回的内存,假设您可以看到具有malloc()返回的指针的变量.

所以在你的代码中,如果t是全局的,它将在main和funct()中可见,是的,你可以在两者中使用它.

事实上,正如之前的答案所提到的,funct()不知道是什么,因为t的声明和定义是主要的; 功能超出了范围.如果 funct知道什么是t ,那么你分配给t的内存在funct中使用.