DfrDkn
DfrDkn

Reputation: 1380

How heaps reference is stored in stack?

I was reading memory management and completely confused by following things. Please explain me. I am not able to clear my concept.

  1. Every heap's root node's reference resides in stack. Why is it necessary?
  2. Objects or reference type's requires stack space also along with Heap?

I know these questions are very basic or may be wrong prediction of mine. But I am totally confused.

Please Explain.

Upvotes: 0

Views: 53

Answers (1)

Youngdo Lee
Youngdo Lee

Reputation: 158

Let's see an example in C language representation:

void foo(void)
{
    char *heap;

    heap = malloc(4096);

    memset(heap, 0xff, 4096);

    free(heap);
}

If you need 4096 bytes heap memory, you should allocate memory in the heap. In addition, you need to keep the memory's starting address(pointer) to manipulate the heap memory allocated before. So you need additional pointer variable heap which holds a pointer to the heap memory. Imagine that heap is absent, how do you manipulate the heap memory like belows:

void bar(void)
{
    // allocated 4096 bytes heap memory.
    // but there is no pointer variable to keep its address
    malloc(4096);

    // how do you manipulate the memory?
    memset(???, 0xff, 4096);

    // how do you free the memory?
    free(???);
}

Upvotes: 1

Related Questions