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

后端 未结 4 1440
礼貌的吻别
礼貌的吻别 2020-12-16 23:31

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 func

4条回答
  •  误落风尘
    2020-12-17 00:06

    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.

提交回复
热议问题