Improvements for this C++ stack allocator?

前端 未结 4 2007
广开言路
广开言路 2020-12-31 21:42

Any suggestions for my stack based allocator? (Except for suggestions to use a class with private/public members)

struct Heap
{
    void* heap_start;
    voi         


        
相关标签:
4条回答
  • 2020-12-31 22:03

    Your heap doesn't allow deallocation. How will you use it for objects allocated with new in C++?

    0 讨论(0)
  • 2020-12-31 22:16
    size_t new_end = ((size_t) heap_end) + bytes;
    

    Not good, never do things like that, you assume that sizeof(size_t)==sizeof(void*), also what happens if bytes==(size_t)(-1) this would not work

    Additionally, you need make sure that pointers that you are return are aligned. Otherwise you would have problems. So you need to make sure that bytes are multiple of 4 or 8 according to your platform.

    class {...
    char *max_end,*head_end,*heap_start;
    };
    
    ...
    max_end=heap_start+size;
    ...
    bytes=align_to_platform_specific_value(bytes);
    if(max_end-heap_end >= bytes) {
       void* output = (void*)heap_end;
       heap_end+=bytes;
       return output;
    }
    throw std::bad_alloc();
    

    Suggestion? Do not reinvent the wheel. There are many and good pool libraries.

    0 讨论(0)
  • 2020-12-31 22:26

    Two obvious problems:

    1/ You don't have a deallocate().

    2/ A deallocate() will be very hard to write with your current strategy unless you're always going to deallocate in the exact reverse order of allocating. You'll need to cater for the case where a client wants to deallocate memory in the middle of your used section.

    Of course, if you do deallocate in reverse order, (2) is not a problem. And if you never free memory at all, (1) is also not a problem.

    It depends on what you want it to do.

    0 讨论(0)
  • 2020-12-31 22:28

    You've implemented a stack based allocator. You can't free up without leaving gaps. Usually a pool refers to a block of contiguous memory with fixed sized slots, which are doubly linked to allow constant time add and delete.

    Here's one you can use as a guide. It's along the same lines as yours but includes basic iterators over allocated nodes, and uses templates to be type aware.

    0 讨论(0)
提交回复
热议问题