How to allocate memory space without using malloc or a new operator?

When my friend interviewed yesterday, he was asked a question: Implement a function that allocates memory space without using the * alloc or new operator, and the function should return a pointer to the address. Neither he nor I can find an answer.

+6
source share
4 answers

I think this question is more of a mystery than a question that shows programming experience. My solution would be to allocate a global byte array that will be used instead of the heap:

char heap[MAX_ALLOWED_MEM]; /* The following function uses 'heap' as raw memory! void* like_malloc(size_t bytes); ... */ 
+15
source

Depending on your platform, you have several options:

  • Since this is C ++, you can trick and call one of the STL allocators . I doubt the interviewer wanted to, but who knows for sure?
  • You can always use fixed-size pools, as several answers suggest.
  • sbrk also an option, but its use is not recommended, and it is no longer part of POSIX.
  • You can also use mmap (or VirtualAlloc or CreateFileMapping on Windows) as a memory source, but if you want chunks of memory to be smaller than entire pages, you still need to write code to control the memory returns these functions.

Your allocator should ensure that the memory alignment is correct for your platform: on some systems, non-smooth access to memory is an invalid operation and other performance is included there compared to aligned access. In real, production code, you also probably want to provide a free operation to avoid all system memory and locks to ensure the security of your heap.

+3
source

You can do this with a system call such as sbrk (), and not with a C library function or C ++ language. However, there is absolutely no reason for this, so this is a very difficult question.

+2
source

Super simple that never gets free.

 class allocator{ static char mem_pool[1048576]; char* place; public: allocator(){ place = mem_pool; } allocator(const allocator& a){ place = a.place; } char* alloc(size_t size){ char* ret = place; place += size; return ret; } } 
+1
source

Source: https://habr.com/ru/post/886574/


All Articles