2
votes

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!

1
You may want to take a look at this SO question/answer.Robert Crovella
I already had a look at the question, but the answer wasn't very helpful, it didn't solve the problem.arngineer
Is the memory being allocated without a problem ? Check the return values (if cudaMalloc here)! If you are trying to a pointer to unallocated space it would likely crash.Pavan Yalamanchili
Yes, the allocation is successful. In a more complex MEX file, I can use the allocated memory for computations. Still MATLAB crashes when clearing the MEX file.arngineer

1 Answers

2
votes

Change declaration of:

void clearMemory(void)

to:

void *clearMemory(void)