Matlab crashes when manipulating an array generated by a mex function

1 次查看(过去 30 天)
Dear all,
I have written a Mex-function that generates an array. Actually, it is a topological sort algorithm. Now let's say I call this function
A = tsort(B); % contains a call to the mex function
A = otherfunction(A); % other function that modifies A contains only matlab code
then it happens quite often that Matlab crashes when calling otherfunction, even after minutes between my call to tsort and otherfunction. Did anyone experience such problems with his or her code. By the way, I am using Windows 7 64bit, Matlab 2012a and Microsoft Software Development Kit (SDK) 7.1 as compiler.
Thanks for your help, Anon
  8 个评论
Anon
Anon 2013-1-24
Hi Colin,
I intend to work with uint32 in Matlab, since some of matrices I work with require large amounts of memory.
Thanks, Anon
James Tursa
James Tursa 2013-1-24
@anon: The mex function is likely corrupting memory but that corruption isn't detected until later on after the mex routine has returned control back to MATLAB. E.g., the mex routine might have corrupted another variable in the workspace that has nothing to do with the mex routine, and it isn't until you get back to MATLAB and do downstream stuff that the error has an effect and crashes MATLAB. If you are unfamiliar with debugging then I suggest you follow my advice and put in lots of checks all over your code to detect when you are out-of-bounds or dereferencing a NULL pointer etc.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2013-1-24
编辑:Jan 2013-1-24
It is a bad idea to use int * pointers on a 64 bit system. mwSize and mwIndex is smarter and avoids the typical crashes.
When ix is a pointer to a UINT32 array, use a uint32_T * to access its elements instead of an int.
You check c to be smaller than 0, but are you sure than mwIndex is signed at all? If your algorithm required a signed type, use mwSignedIndex explicitly.
It is easy to write a C-Mex file, which corrupts the memory. Frequently the crash does not occur inside the C-Mex, because C is very tolerant to brute memory access, in opposite to Matlab.
  1 个评论
Anon
Anon 2013-1-28
Thank you everyone for your replies. I have changed the pointer class and used mwSignedIndex as suggested by Jan. So far, I haven't experienced any crashes anymore.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by