c++ - Is it possible to use operator new to allocate from elsewhere than the heap? -


here context of application : i'm working on embedded system uses ram different devices. 1 part in internal ram of microcontroller (128kb) , other part external ram (1mb). these memories mapped address space of microcontroller, in non contiguous regions.

the internal ram used system stack, tasks stacks , heap. external ram used statically allocated data (pools, buffers, , "static ..." stuff)

i trying implement simple memory management structure, , part of able create allocator use allocation algorithm of operator new using memory source, not system heap memory region elsewhere. know if possible ?

an example of use reserve 100kb of external ram , create allocator manage it, , give specified task need memory.

static const uint8_t* rambase = reinterpret_cast<uint8_t*>(0x80000000); static const uint32_t ramareasize = 0x19000; //100kb bufferallocator allocator(rambase, ramareasize);  //... //assuming operator new overloaded use bufferallocator myobject * obj = new (allocator) myobject(some, parameter); //... 

the question : how (if possible) can implement bufferallocator in order use operator new manage raw memory area ?

void* bufferallocator::allocate(uint32_t bytes) {     //i write     //and let responsibility manage memory area "new"     //so don't have reimplement (or reuse) different custom       // allocator     return ::operator new(rambase, ramareasize, bytes) }  

i faced same problem well, , solution find write own malloc , free. didn't need special, modeled code after shown in k&r's the c programming language (they have naive example documented).

i created 2 heaps: 1 internal memory, , 1 external memory. stack in entirely different block of memory (ccram on stm32f4), didn't need worry sbrk. however, did have know start address of internal sram heap based on size of data , bss segments. determined extern symbols injected linker script.

i have enough information heap know current size, amount of free space, , whether there enough contiguous memory perform allocation. if there's not enough in internal sram, tries external sram. if there's not enough memory there, it's no different default malloc running out of memory.

i using gnu toolchain, able employ --wrap option override c standard library's default malloc, free, realloc, , calloc (actually malloc_r, free_r, realloc_r , calloc_r since i'm using newlib). since new , delete call malloc , friends, able make work (at least needs).

i'm not terribly confident approach, it's best within limitations of abilities. consider scrutiny.

i interested in knowing simpler solution.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -