1

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).

I used 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()?

user997112
  • 29,025
  • 43
  • 182
  • 361
  • If you are going to mess around with `brk` yourself, then very likely the libstdc++ / libc will not work properly (they rely on a working `malloc`). Are you fine with it? – Guilherme Bernal Jan 01 '14 at 01:14
  • 4
    Instead of using `brk`, use `mmap()` on `/dev/zero` to get a block of memory. http://stackoverflow.com/questions/8507945/mmap-with-dev-zero – Barmar Jan 01 '14 at 01:16
  • @Barmar I had a look at mmap() vs brk() and it seems the difference is that mmap() can allocate at various positions (brk cannot) but is slower than brk()? – user997112 Jan 01 '14 at 01:21
  • @GuilhermeBernal I dont understand what you mean by it will "mess around" by it? What do you mean by this/why would it interfere? – user997112 Jan 01 '14 at 01:21

1 Answers1

3

Using brk will probably interfere with the regular C/C++ memory allocator. Even if you don't use regular new or malloc() in your code, it might be used in libraries.

If you want to manage your own memory, use mmap() on /dev/zero to get an empty block of memory. I think you can do this repeatedly to get new blocks.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What do you mean by interference with the regular C/C++ memory allocator? Im not doubting it- just wanting to learn what you mean/what is happening. – user997112 Jan 01 '14 at 01:22
  • 1
    `malloc` probably assumes that it's the only code that's calling `brk`, so everything in there is its own heap. – Barmar Jan 01 '14 at 01:23
  • Oh I get you- so it wouldnt be a problem if I had no other heap-allocated memory but if I allocated other objects on the heap via malloc/new I could have issues? – user997112 Jan 01 '14 at 01:33
  • Right. And like we said, if you call any library functions, they might allocate on the heap. – Barmar Jan 01 '14 at 01:34
  • e.g. Boost library etc – user997112 Jan 01 '14 at 01:35