问题
在使用matlab的csfunction编程时出现了错误:matlab调用.mex函数时,第一次调用正常,第二次调用出现matlab闪退、或者卡死无反应的错误,然后崩溃信息提示堆损坏。然而matlab没有如vs那样方便的编辑器和调试器,因此在找错误的时候非常困难。
问题分析
-
猜想可能是数组越界等导致的内存问题,然后在网上找到这样一篇文章:
有关奇葩的mex编程时的matlab出现栈内存错误的问题
,大致分析了出错的原因。 - matlab提供的调试器功能有限,可以借助第三方软件进行调试,matlab的官方文档内介绍了有关debug C mex S-Functions的技巧和方法。
解决措施
官方文档内介绍:
Debugging C MEX S-Functions Using the Microsoft Visual C++ .NET Environmen Before beginning the example, save the files sfcndemo_timestwo and timestwo.c into your working folder.
- Open the Simulink model sfcndemo_timestwo.c
-
Create a version of the MEX file that you can debug by compiling the C file using the mex command with the -g option.
mex -g timestwo.c
The -g option creates the executable timestwo.mexw32 with debugging symbol included. At this point, you may want to simulate the sfcndemo_timestwo model to ensure it runs properly. - Without exiting the MATLAB environment, start the Microsoft Development Environment.
- From the Microsoft Development Environment menu bar, select Tools > Debug Processes.
- In the Processes dialog box that opens, select the MATLAB.exe process in the Available Processes list and click Attach.
- In the Attach to Process dialog box that opens, select Native in the list of program types and click OK. You should now be attached to the MATLAB process.
- Click Close on the Processes dialog box.
-
Clear the MEX functions in MATLAB using the clear command.
clear mex
- From the Microsoft Development Environment File menu, select Open > File.Select the timestwo.c source files from the file browser that opens.
- Set a breakpoint on the desired line of code by right-clicking on the line and selecting.Insert Breakpoint from the context menu. If you have not previously run the model, the breakpoint may show up with a question mark, indicating that the executable is not loaded. Subsequently running the model loads the .mexw32 file and removes the question mark from the breakpoint.
- Start the simulation from the sfcndemo_timestwo Simulink model. You should be running the S-function in the Microsoft Development Environment and can debug the file within that environment.
按照上述方法可以在vs内对C Mex function程序进行调试,查看数组越界情况,最终找到问题所在。
版权声明:本文为Maryman原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。