Overload remove and get size?

I am currently writing a small custom Allocator memory block in C ++ and want to use it along with overloading the new / delete operator. In any case, my Allocator memory basically checks to see if the requested memory exceeds a certain threshold, and if so, malloc is used to allocate the requested piece of memory. Otherwise, memory will be provided by some fixedPool . which usually works, but for my highlight function is called:

 void MemoryManager::deallocate(void * _ptr, size_t _size){ if(_size > heapThreshold) deallocHeap(_ptr); else deallocFixedPool(_ptr, _size); } 

So, I need to specify the size of the selected fragment in order to free up space in the right place.

Now the problem is that the delete keyword does not contain any hint at the size of the fragment to be deleted, so I will need something like this:

 void operator delete(void * _ptr, size_t _size){ MemoryManager::deallocate(_ptr, _size); } 

But as far as I can tell, there is no way to determine the size inside the delete statement. If I want everything to be as it is now, I must save the size of the pieces of memory myself

+4
source share
4 answers

Allocate more memory than necessary and store size information there. This is what your system distributor probably does. Something like this (demonstrate with malloc for simplicity):

 void *allocate(size_t size) { size_t *p = malloc(size + sizeof(size_t)); p[0] = size; // store the size in the first few bytes return (void*)(&p[1]); // return the memory just after the size we stored } void deallocate(void *ptr) { size_t *p = (size_t*)ptr; // make the pointer the right type size_t size = p[-1]; // get the data we stored at the beginning of this block // do what you need with size here... void *p2 = (void*)(&p[-1]); // get a pointer to the memory we originally really allocated free(p2); // free it } 
+5
source

You can save the memory address card in the size for your memory allocated by the pool. When you delete, check if the pointer is on the map if it deletes this size if it does not cause regular deletion.

+2
source

For a class type, C ++ already supports it directly. For nonclass types, you need to save the size manually, as shown by another solution.

 struct MyClass { void operator delete(void *p, size_t size) { MemoryManager::deallocate(p, size); } }; 
+2
source

As in C ++ 14, the standard supports the second parameter size in the global delete function. Therefore, I want you to want to make this possible now.

http://en.cppreference.com/w/cpp/memory/new/operator_delete

+1
source

Source: https://habr.com/ru/post/1305933/


All Articles