"clear all" causes seg fault due to failure of calling a class destructor
Show older comments
Hello all,
Let me briefly describe my code. I made mex functions to access a C++ class. Based on my mex functions, I made an MATLAB class that mimics the original C++ class. Basically, the C++ class's constructor gets called in the MATLAB class's constructor, and likewise, the C++ class's destructor gets called in the MATLAB class's destructor, i.e. the delete() function. In the C++ class's constructor, I dynamically allocate some memory space and free the space in the C++ class's destructor.
My code worked fine, but I found it can cause seg fault at a particular case, which is the case that I run "clear all" in MATLAB. Specifically, I got a seg fault error when I run "clear classes." It seems to me at both cases the C++ class's destructor, which de-allocate memory, cannot be called. However, it does get called for "clear variables."
The MATLAB documentation says there are differences between "clear" and "delete," but I cannot find some answers to my problem. I wonder if there is a way to free memory space properly by calling the destructor for "clear all" and "clear classes." Look forward to hearing some advice.
K. Lee.
Answers (2)
Daniel Shub
on 10 Aug 2011
0 votes
The clear command does not delete an object. An object is only deleted if all references to the object are cleared from memory. Is it possible that you have a reference to the object someplace that is being cleared (possibly in the application data of a figure or a callback of a timer object). I would bet strange things will happen if you clear classes without all your instances of the class not being cleared.
3 Comments
Kyunghoon Lee
on 11 Aug 2011
James Tursa
on 11 Aug 2011
Are you using a mexAtExit function?
Daniel Shub
on 11 Aug 2011
You really do not want to call delete when clear is called. This would screw up anything that depends on a "saved" handle to the object.
Daniel Shub
on 11 Aug 2011
Are you defining your delete method in the a methods block in the classdef file or in a separate file within the @foo directory (where foo is the name of your class)? I have had problems getting the overloaded delete method to be called when I define it is a separate file. It seems to help if I add a methods block with the footprint of the delete function into the classdef file.
methods
delete(Obj);
end
1 Comment
Kyunghoon
on 3 Sep 2011
I have the delete function defined in the classdef file. I wonder if I can overload "clear" so that when "clear myobj" is called, I can invoke the delete method.
Categories
Find more on Class Introspection and Metadata in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!