简体   繁体   English

C ++自定义内存管理使用brk()系统调用来分配内存?

[英]C++ Custom memory management using brk() system call to allocate memory?

I wrote a basic custom memory management allocator which would grab a chunk of memory, pre-create X objects so that whenever I needed to "create" an object I could grab one of the pre-created ones and simply assign data members (memory was already allocated). 我写了一个基本的自定义内存管理分配器,它可以获取一块内存,预先创建X对象,这样每当我需要“创建”一个对象时,我就可以抓住一个预先创建的对象并简单地分配数据成员(内存是已分配)。

I used placement-new : 我使用了placement-new

//Grab a chunk of memory
char* buf = new char [sizeof(X) * num_objs]; 

//Pre-create a lot of objects
for(std::int64_t i=0; i<num_objs; i++){
    char* c = buf + (sizeof(X) * i);

    //This line creates the Order object at location c
    X* x = new(c)X;
}

//Assign data members to objects
for(std::int64_t i=0; i<num_objs; i++){
    char* buf_loc = buf + (sizeof(X) * i); 
    X* my_x = reinterpret_cast <X*> (buf_loc);
    my_x->a = 1;
    my_x->b = 2;
    my_x->c = 3;
    my_x->d = 4;
}

How easy/practical would it be to change the above and directly grab memory from the OS using brk() ? 改变上述内容并使用brk()直接从操作系统中获取内存是多么容易/实用?

Using brk will probably interfere with the regular C/C++ memory allocator. 使用brk可能会干扰常规的C / C ++内存分配器。 Even if you don't use regular new or malloc() in your code, it might be used in libraries. 即使您不在代码中使用常规newmalloc() ,也可以在库中使用它。

If you want to manage your own memory, use mmap() on /dev/zero to get an empty block of memory. 如果要管理自己的内存,请在/dev/zero上使用mmap()来获取空的内存块。 I think you can do this repeatedly to get new blocks. 我认为你可以反复这样做以获得新的块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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