I try to run some CUDA MEX files in MATLAB. (CUDA 5.0, Linux x86, MATLAB R2012a)
The Problem is: EVERY MEX-file which uses some kind of cudaMalloc/cudaFree crashes when I unload the function from inside MATLAB.
Here is a very simple example (but this also applies to the official NVidia samples):
#include <stdint.h>
#include "mex.h"
static float* d_test = NULL;
void clearMemory(void)
{
cudaFree(d_test);
}
void cudaTest()
{
if (d_test == NULL)
{
cudaMalloc((void**) &d_test, 10000 * sizeof(float));
}
// Do some CUDA computations here...
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mexAtExit(clearMemory);
cudaTest();
}
And this is how I compile the code:
function CUDA_COMPILE( func_name )
eval(sprintf('!nvcc -I"%s/extern/include" --cuda "%s.cu" --output-file "%s.cpp"', matlabroot, func_name, func_name));
mex('-I/usr/local/cuda/include', '-L/usr/local/cuda/lib', '-lcudart', [func_name '.cpp']);
end
The code compiles and runs fine, but once I clear the MEX function from memory, MATLAB crashes, i.e. on:
clear freeCudaMemory
Do you have any idea what might cause this problem? Thanks in advance!