Improvements for this C++ stack allocator?

前端 未结 4 2032
广开言路
广开言路 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: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.

提交回复
热议问题