简体   繁体   中英

c++ memory allocation procedure for pointers

In MSVC++, First i created a vil_image_view container(im_1) and allocated the memory by giving the size (rows and columns), then i assigned a NULL value to that pointer, After both these steps i created another image container(im_2) and did the same procedure to allocate the memory and i have noticed that memory addresses of both containers were same. Is that completely random? Or How that allocation and deallocation happens?

vil_image_view is an image container from vxl library and it is a shared pointer, when the reference counter becomes zero, the object will be automatically deleted

vil_image_view<float> im_1;

im_1.set_size(n,m);  //0x05773ff0

im_1 = NULL;        //0x00000000

vil_image_view<float> im_2;

im_2.set_size(n,m);  //0x05773ff0

The following code returns the same address compiled by VC and run on windows.

#include <iostream>

using namespace std;

int main()
{
    int *i = new int[100];
    std::cout << i << std::endl;
    delete [] i;

    int *j = new int[100];
    std::cout << j << std::endl;
    delete [] j;

    return 0;
}

Different system may have different memory allocation & deallocation strategies. But generally memories are maintained by linked lists. A block of free memory (with header) will point to the next free memory. The already allocated ones will be jumped over. Once memory is freed, it might be required to merge with existing free blocks to form a larger block.

When allocating memory, the simplest strategy is to search from the list head, and find the first free block that has size larger than the required size.

The following code, will most probably not return you the same address.

#include <iostream>

using namespace std;

int main()
{
    int *i = new int[100];
    std::cout << i << std::endl;
    delete [] i;

    int *j = new int[10000];
    std::cout << j << std::endl;
    delete [] j;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM