Skip to content

Reproducible crash in mi_stats_add() on thread-end #1320

Description

@HSNB

The following code will very likely crash after ~20 seconds due to bad pointer.

std::mutex mtx;
std::vector<mi_heap_t*> heaps;

void cruncher()
{
	srand((unsigned int)time(0));

	for (size_t i = 0; i < 1000uz; ++i) {
		switch (rand() % 3) {
		case 0: //create a new heap
			{
				if (const auto new_heap = mi_heap_new()) {
					std::unique_lock lock(mtx);
					heaps.emplace_back(new_heap);
				}
			}
			break;
		case 1: //allocate from a random heap
			{
				std::unique_lock lock(mtx);
				if (heaps.size() > 0)
					(void)mi_heap_malloc(heaps[0], (size_t)rand() % 9000);
			}
			break;
		case 2: //destroy a random heap
			{
				std::unique_lock lock(mtx);
				if (heaps.size() > 0) {
					mi_heap_destroy(heaps[0]);
					heaps.erase(heaps.begin());
				}
			}
			break;
		}
	}
}

void main()
{
	for (int x = 0; x < 128; ++x) {
		std::vector<std::jthread> threads;

		for (int i = 0; i < 512; ++i)
			threads.emplace_back(std::jthread(cruncher));

		cruncher();
	}
}
Image

stats pointer is always 0x7b8

I believe mi_heap_new() is thread-safe, therefore it is not protected by a mutex, though the crash happens either way.

Version: static library v3.3.2 dev3 branch

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions