How delete mesh data safely?

I’m doing some test and running Blender in debug mode, always crash.

I want to delete mesh data and create a new one.

this is a snippet of the code:


import bpy


print("A")
o = bpy.context.active_object
print("B")
o.select = False
print("C")
o.data.user_clear()
print("D")
bpy.data.meshes.remove(o.data)
print("E")
objmesh = bpy.data.meshes.new('Supercubo')
print("F")
o.data = objmesh

The console shows this:

ED_undo_push: Run Script
A
B
C
D
E
F
Error: EXCEPTION_ACCESS_VIOLATION

How can I delete and assign a new one data mesh without error?

PS: If I run Blender in normal mode, works fine.

It’s necessary to create before a mesh data, replace the object mesh data, and THEN delete old mesh data. If you delete the mesh data before, in some OS get an error and Blender crash.

The weird thing is that works in some OS and depending if you run in Debug or Normal mode.

You shouldn’t ever use user_clear() actually, because it will circumvent all safe guards that prevent use-after-free crashes. Instead, you should clear all references to that mesh, then delete. Finding all references is unfortunately hard.