Can all functions in a thread have access to dynamically allocated memory (heap) even without passing pointer or is it local to a function


I have a very basic question and need help. I am trying to understand what is the scope of a dynamically allocated memory (on heap).

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

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

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

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);

//-----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;

Here, can I access structure t in funct() even though the memory is allocated in main() without passing argument (pointer to t to function funct) – since heap is common to a thread? What difference will it make if I define struct node * t = NULL outside of main() as a global variable and is there anything wrong with it?

Best Solution

When you use malloc(), the memory returned by that can be accessed anywhere in your code, assuming that you can see the variable which has the pointer returned by malloc().

So in your code, if t was global, it would be visible in main and in funct(), and yes, you could use it in both.

As it is, as previous answers have mentioned, funct() has no idea what t is, because the declaration and definition of t are in main; t is out of scope in funct. The memory you've allocated onto t would be useable in funct, if funct knew what t was.

Related Question