MATLAB: How to enhance the memory allocation in the MEX-file

allocationdynamicfreemallocMATLABmemorystatic

How do I enhance the memory allocation in my MEX-file?
I am trying to create large arrays in my MEX-file; however when I try to run the MEX-file in MATLAB, it crashes my MATLAB session. I am assuming that this is because of some limit on how much memory can be allocated depending upon the operating system. But I would like to know some way to enhance the execution of the program so that MATLAB will not crash.

Best Answer

The reason MATLAB crashes when you run your application is because there isn't enough memory on the stack. Since the stack memory is shared with MATLAB, which is already using a lot of the memory, there is not enough memory left on the stack for the memory allocation done in your code.
A solution to this problem is to use the dynamic allocation of memory using the MALLOC command in C. This will force the memory allocation to be done on the heap. However, there is still an upper limit of how much memory can be allocated using MALLOC which will be governed by the operating system. Also make sure you free the memory allocated with MALLOC to prevent memory leaks. You will have to use the FREE command in C to free up the memory.