MySQL Internals How to allocate memory
← Back to MySQL Internals overview page
[edit] How to allocate memory in the MySQL server (sql directory)
The basic logic to use:
All things that are used only for the duration of a query are allocated in THD::mem_root through sql_alloc() or thd->alloc() except:
- Things that may grow, like string buffers of type String. See sql/sql_string.cc.
- Large blocks of memory used in one state of the query that can be released early. These are things like sort buffers, range trees, etc.
- Things in libraries that are outside of MySQL's control (like hash tables).
Things that are needed a longer time should be alllocated with my_malloc() or through another MEMROOT.
Some objects have their own MEMROOT:
- TABLE
- TABLE_SHARE
- Query_arena
- st_transactions
[edit] How to allocate memory in a library or storage engine
For the simple case, use the functions in mysys/my_malloc.c:
- void *my_malloc(size_t size, myf my_flags);
- void *my_memdup(const void *from, size_t length, myf my_flags);
- char *my_strdup(const char *from, myf my_flags);
- char *my_strndup(const char *from, size_t length, myf my_flags);
- void my_free(void *ptr, myf my_flags);
Alternatively, if you want to allocate many pieces at once, use my_multi_malloc() from mysys/mulalloc.c
- void *my_multi_malloc(myf myFlags, ...)
For the complex case where you want to allocate a lot and free things at once,
use the MEM_ROOT object defined in mysys/my_alloc.c
Functions to use:
- void init_alloc_root(MEM_ROOT *mem_root, size_t block_size, size_t pre_alloc_size);
- void *alloc_root(MEM_ROOT *mem_root, size_t length);
- void *multi_alloc_root(MEM_ROOT *root, ...);
- void free_root(MEM_ROOT *root, myf MyFlags);