Skip to content

Added mi_visit_blocks to visit all blocks of all heaps in a thread#1241

Open
DV-AG wants to merge 1 commit intomicrosoft:mainfrom
DV-AG:visit-all-blocks
Open

Added mi_visit_blocks to visit all blocks of all heaps in a thread#1241
DV-AG wants to merge 1 commit intomicrosoft:mainfrom
DV-AG:visit-all-blocks

Conversation

@DV-AG
Copy link

@DV-AG DV-AG commented Mar 9, 2026

Added a method "mi_visit_blocks()" in src/heap.c to visit all blocks of all heaps in a thread and made required changes in include/mimalloc.h by adding

mi_decl_export bool mi_visit_blocks(const mi_heap_t* heap ,bool visit_blocks, mi_block_visit_fun* visitor, void* arg);

Below is the function I added

bool mi_visit_blocks(const mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {
  mi_assert_internal(heap != NULL);
  if (heap == NULL) return false;
  mi_heap_t* curr = heap->tld->heaps;
  while (curr != NULL) {
    mi_heap_t* next = curr->next;
    if(!mi_heap_visit_blocks(curr, visit_blocks, visitor, arg)){
      return false;
    }
    curr = next;
  }
  return true;
}

This function was tested with the below code

#include <stdio.h>
#include <stdlib.h>
#include "mimalloc.h"

static int block_count = 0;


bool visit_block(const mi_heap_t* heap,
                 const mi_heap_area_t* area,
                 void* block,
                 size_t block_size,
                 void* arg)
{
    block_count++;
    printf("Visited block %p size=%zu\n", block, block_size);
    return true;   // continue visiting
}

int main() {

    
    mi_heap_t* heap = mi_heap_new();

    if (heap == NULL) {
        printf("heap creation failed\n");
        return 1;
    }

    
    void* p1 = mi_heap_malloc(heap, 64);
    void* p2 = mi_heap_malloc(heap, 128);
    void* p3 = mi_heap_malloc(heap, 256);

    printf("Allocated blocks: %p %p %p\n", p1, p2, p3);

   
    mi_visit_blocks(heap, true, visit_block, NULL);

    printf("Total blocks visited: %d\n", block_count);

    /* cleanup */
    mi_free(p1);
    mi_free(p2);
    mi_free(p3);

    mi_heap_destroy(heap);

    return 0;
}

@DV-AG
Copy link
Author

DV-AG commented Mar 9, 2026 via email

@DV-AG
Copy link
Author

DV-AG commented Mar 9, 2026

@microsoft-github-policy-service agree

@DV-AG
Copy link
Author

DV-AG commented Mar 9, 2026

Fixes #1180

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants