Skip to content

How to restore the initial state of the module? #1163

@gongshuaiqi

Description

@gongshuaiqi

I want to new a heap for a module. To avoid memory fragmentation, when the module is idle, I want to restore the initial state of the heap. How should I do this? Thank you.

#include <sys/mman.h>
#include <mimalloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int main() {
const size_t size = 1UL << 30; // 1GB
int protection = PROT_READ | PROT_WRITE;
int flags = MAP_ANONYMOUS | MAP_SHARED;
void* addr = mmap(NULL, size, protection, flags, -1, 0);

if (addr == MAP_FAILED) {
    fprintf(stderr, "Error: mmap failed\n");
    return 1;
}

memset(addr, 0, size);
printf("addr: %p, end:%p\n", addr, (char*)addr + size);

// Tell mimalloc we (the user) own the region (own=false).
// => We are responsible for calling munmap.
mi_arena_id_t arena_id;
bool ok = mi_manage_os_memory_ex(addr, size,
                                 /*commit?*/ true,
                                 /*allow_large?*/ false,
                                 /*is_pinned?*/ false,
                                 /*alignment*/ -1,
                                 /*own?*/ false, 
                                 &arena_id);
if (!ok) {
    fprintf(stderr, "Error: mi_manage_os_memory_ex failed\n");
    munmap(addr, size);
    return 1;
}

// Create a custom heap in that arena
mi_heap_t* my_heap = mi_heap_new_in_arena(arena_id);
if (!my_heap) {
    fprintf(stderr, "Error: could not create heap\n");
    munmap(addr, size);
    return 1;
}

// Allocate memory from our custom heap
void* p1 = mi_heap_malloc(my_heap, 1 * 1024 * 1024); // 1MB
void* p2 = mi_heap_malloc(my_heap, 1 * 1024 * 1024); // 1MB
printf("p1=%p, p2=%p\n", p1, p2);

// Free the allocated blocks
mi_free(p1);
mi_free(p2);

// Delete the heap
mi_heap_delete(my_heap);

// Now we can safely unmap, since mimalloc doesn't "own" the region
munmap(addr, size);

return 0;

}

(1)When the "own" parameter of mi_manage_os_memory_ex() is set to true, Do I still need to munmap?

(2)Should I use mi_heap_delete or mi_heap_destroy to restore the initial state of the heap?

(3)After restoring to the initial state, should I call mi_heap_new_in_arena(arena_id) to re-allocate a heap?

(4)I found that after calling mi_heap_destroy and mi_heap_new_in_arena(arena_id), mi_option_is_enabled(mi_option_show_errors) changed from 0 to 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions