qwerty
qwerty

Reputation: 160

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

When my friend had his interview 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 the answer.

Upvotes: 8

Views: 6922

Answers (4)

Left For Archive
Left For Archive

Reputation: 2666

Depending on your platform you have a few options:

  • Since this is C++, you can cheat and invoke one of the STL allocators. I doubt that's what the interviewer wanted, but who knows for sure?
  • You can always use fixed-size pools as a couple of the answers suggest.
  • sbrk is also an option, but its use is discouraged and it's no longer part of POSIX.
  • You can also use mmap (or VirtualAlloc or CreateFileMapping on Windows) as a source of memory, but if you want memory chunks smaller than whole pages you'll still need to write some code to manage the memory these functions return.

Your allocator should ensure memory is properly aligned for your platform: on some systems, unaligned memory access is an invalid operation and on others there's a performance hit vs. aligned access. In real, production code you'd also likely want to provide a free operation to avoid taking over all the system's memory and locking to make your heap thread-safe.

Upvotes: 3

Null Set
Null Set

Reputation: 5414

A super simple one that never frees.

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;
        }
}

Upvotes: 1

Khaled Alshaya
Khaled Alshaya

Reputation: 96939

I think the question is more of a puzzle than a question that shows experience with programming. My solution would be allocating a global byte-array, that would 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);
   ...
*/

Upvotes: 16

user2100815
user2100815

Reputation:

You can do it via a system call such as sbrk(), rather than using a C library function or a C++ language feature. There is absolutely no reason to do this, however, so this is a very crappy question.

Upvotes: 2

Related Questions