Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Memory allocators

I've heard about people using custom memory allocators for their project, particulary in C++.

  • What is a custom memory allocator, compared to malloc?

  • Isn't malloc the lowest level you can go already?

like image 253
Raik Avatar asked Jan 09 '11 23:01

Raik


People also ask

How does a memory allocator work?

Techopedia Explains Memory AllocationPrograms and services are assigned with a specific memory as per their requirements when they are executed. Once the program has finished its operation or is idle, the memory is released and allocated to another program or merged within the primary memory.

What are allocators good for?

Furthermore an allocator can be used to perform different techniques of memory management, eg stack allocation, linear allocation, heap allocation, pool allocation etc. This is the normal flow of calls, but an application can instead call malloc/free, or new/delete or even the OS APIs directly.

What can I use to deallocate memory?

To deallocate previously allocated memory, we will use the standard library function realloc(). The "realloc()" function declaration from "stdlib.

How can we dynamically allocate memory in C?

C malloc() method The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.


1 Answers

A memory allocator isn't lower level than malloc. (The default allocator typically calls malloc directly or indirectly)

An allocator just allows you to specify different allocation strategies. For example, you might use an allocator which calls malloc once to retrieve a large pool of memory, and then for subsequent allocation requests, it just returns a small chunk of this pool.

Or you may use it as a hook to allow you to perform some additional task every time memory is allocated or freed.

As to your second question, malloc is the lowest you can go without losing portability. malloc is typically implemented using some OS-specific memory allocation function, so that would be lower level still. But that's unrelated to your main question, since C++ allocators are a higher-level abstraction.

like image 53
jalf Avatar answered Oct 18 '22 04:10

jalf