pointers to the heap.

27 Oct 2011

I wrote the following program to see what happens when pointers to the heap are created:

#include "mbed.h"

class MyTest
{
    public:
        
        char someData[0xFF];
};

MyTest* test(void);

int main() 
{
    MyTest* B1;
    MyTest* B2;
    
    B1 = test();
    B2 = test();
    
    printf("Address of B1 is: %x\r\n", B1);
    printf("Address of B2 is: %x\r\n", B2);
    
    while(1)
    {
    }
}

MyTest* test(void)

    return new MyTest();
}

The result of the program is: 
Address of B1 is: 10000260
Address of B2 is: 10000368

It seems like B1 and B2 are placed directly after each other on the heap. One would expect that if the heap gets 'cleaned up', and the location of the objects are changed during this process ,the pointers will point to the wrong memory locations. This is not the case however. Does the processor use a hardware lookup table to get the memory pointed to by B1 and B2? i.e. are the addresses returned by the program virtual addresses?

27 Oct 2011

What do you mean by "cleaned up"? And why would object locations change all of a sudden?

27 Oct 2011

Whith "cleaned up" I mean heapsort: http://en.wikipedia.org/wiki/Heapsort. During this heapsort the location of the objects are changed.

27 Oct 2011

I don't think that description applies to the memory heap, it is a method that is used to sort data in a given block using a technique that handles the data similar to the memory heap.

It wouldn't make any sense to clean up a heap this way, anything still in the heap would indeed be scrambled. The exception to this is if the heap supports handles (a pointer to a pointer). The location of the handle would be fixed in memory but the data block it points to isn't.

"Handle" blocks are the only sort you could do a clean up on, Pointer blocks have to be left alone.