Here’s another way to crash MATLAB!
Now that we know MATLAB’s memory manager has some problems with actually cleaning up too many objects at once, we can have some fun with it!
function pushdown(N, crash)
%an N of more than about 1000000 with crash=1 is interesting.
a = {};
for i = 1:N
a = {rand() a};
end
if ~exist('crash', 'var') || ~crash
%feed it to matlab's deallocator one piece at a time, or it will choke.
for i = 1:N
a = a{2};
end
end
end
First try running:
>> pushdown(1000000)
Then try:
>> pushdown(1000000, 1)
What do you get? I get a hard crash.
So not only can you blow the interpreter stack with deallocation, you can blow the C stack as well!
I mean, a system can get by for some purposes without garbage collection… but not when reference-counting is done this badly.
cellocgw said,
June 4, 2012 at 6:32 am
R2011a , win7 x64, 8 Gig RAM: I tried pushdown(1e8,1). Took forever but did not crash. It did leave over 6.5Gig allocated to Matlab, which I think I could only free up by quitting the app.
crowding said,
June 4, 2012 at 5:59 pm
Interesting. I got crashes on r2010a/Mac/32bit and R2011b/Linux/64
cellocgw said,
June 5, 2012 at 5:54 am
Dunno whether Java version matters: $ java -version
java version “1.6.0_31″
Java(TM) SE Runtime Environment (build 1.6.0_31-b05)
Java HotSpot(TM) Client VM (build 20.6-b01, mixed mode)
jordigh1 said,
June 20, 2012 at 11:29 am
You’re basically overflowing the stack, when the COW semantics incur in calling 1e6 recursive dtor calls, so you’re incurring UB. Octave crashes on my system with this example too, exhibiting UB in its own way. It may happen, by accident, that this call stack depth of 1e6 doesn’t overflow your stack yet.
I’m not too inclined to attempt to “fix” this, since it’s a very contrived example. Does anyone really nest cell arrays to depth 1e6?
crowding said,
August 31, 2012 at 2:39 am
Actually, abusing cell arrays as cons cells is a simple and performant way to accumulate a buffer of data whose size you don’t know at the outset, as I found in some measurements over here (that’s ‘pushdownCell’ in the graph.)
I’m not sure why destructor calls have to be recursive. I know why they are in MATLAB’s reference objects, as in the previous blog, because they made the boneheaded decision to guarantee deterministic destruction, so they made a decision on destruction order and they’re stuck with it.
tug said,
June 27, 2012 at 6:19 am
I am under Windows Xp 32 bit with only 3.25 GB RAM : No crash and immediate answer in 11a,11b ,12a ,12b . the crash only appears with R2010a …. so upgrading seems the good workaround