Blender crashes when running trying to overlap() After a few runs, it is quite certain that the overlap() function is causing blender to quit unexpectedly, I am not sure if the for loop is making blender to run on an infinite loop that cause that.

Or is there a way to write overlap() in a more elegant way to detect if an object is overlaping with another and get the the overlaping object in return.

import bpy
from mathutils.bvhtree import BVHTree
dgraph=bpy.context.evaluated_depsgraph_get()
for obj in bpy.context.scene.objects:
    if obj.name.startswith("M"):
        for obj2 in bpy.context.scene.objects:
            print(BVHTree.FromObject(obj, dgraph).overlap(BVHTree.FromObject(obj2, dgraph)))


there's only 6 objects in the scene with some cubes and cylinders for test.
The script iterates over all objects, including those that aren't meshes. Only determine the overlap for objects with type set to "MESH" and it will work properly.

Your script with the suggested fix:

import bpy
from mathutils.bvhtree import BVHTree

dgraph = bpy.context.evaluated_depsgraph_get()

for obj in bpy.context.scene.objects:
    if obj.name.startswith("M") and obj.type == "MESH":
        for obj2 in bpy.context.scene.objects:
            if obj2.type == "MESH":
                print(BVHTree.FromObject(obj, dgraph).overlap(BVHTree.FromObject(obj2, dgraph)))